//
//  getJobSheetViewController.m
//  HondaPro_2
//
//  Created by glendale on 13-6-13.
//  Copyright (c) 2013年 glendale. All rights reserved.
//

#import "getJobSheetViewController.h"
#import "HomeworkViewController.h"
#import "SignViewController.h"
#import "mm_addAndModifyViewController.h"
#import "mm_multipleCustomerToAllocateViewController.h"
#import "mm_jobItemGroupViewController.h"
#import "CarCalendarQueryViewController.h"
#import "MyAFNetWorkManager.h"
#import "PhotoModel.h"
#import "DiscountItem.h"
#import "UIImageView+WebCache.h"

#import "HJNotConmmingPadModel.h"
#import "HJRepairtGroupModel.h"

#import "HJMakeAppointmentSelectView.h"
#import "CustomizedViewController.h"  //自定义项目新增
#import "ServiceActiveView.h"//服务活动视图
#import "ReasonView.h"//不参加原因
#import "HJRepairGroupViewController.h"

#define REPAIR_TYPE_EXIST_      YES
#define REPAIR_TYPE_NOT_EXIST_  NO
#define STATE_BUTTON_ON_        YES
#define STATE_BUTTON_OFF_       NO


#define customerChargeCode  @"S001"//自费
#define repairChargeCode  @"S004"//保修
#define firstReparirChargeCode  @"S002"//首保
#define firstReparirFreeCode  @"S003"//免费
#define firstReparirActCode  @"S008"//市场活动

typedef enum btnTag
{
    repairItemBtnTag = 10,
    partListBtnTag = 20,
    otherChargeLiatBtnTag = 30,
    addBtnTag = 40,
    modifyBtnTag = 50,
    addResultsTag = 60,//用户陈述、作业指示 编辑 按钮
    modifyResultsTag = 70,
    paiGongBtnTag = 80,
    daYinBtnTag = 90,
    multipleCustomerAllocationJumpBtnTag = 10000
} btnTag;


@interface getJobSheetViewController ()<picRecodeViewControllerDelegate,mm_jobItemGroupViewControllerDelegate,mm_addAndModifyViewControllerDelegate,HJMakeAppointmentSelectViewDelegate,CustomizedViewControllerDelegate,ServiceActiveViewDelegate,ReasonViewDelegate>
/**
 新增按钮
 */
@property(nonatomic,weak)UIButton*addBtn;
/**
 修改按钮
 */
@property(nonatomic,weak)UIButton*modifyBtn;
/**
 自定义按钮
 */
@property(nonatomic,weak)UIButton*customizedBtn;
/**
 维修组合
 */
@property(nonatomic,weak)UIButton*repairGroupBtn;

/**
 用于判断是否是自定义视图展示
 */
@property(nonatomic,assign)BOOL customizedShow;
/**
 用户签字图片
 */
@property(nonatomic,weak)UIImageView*customerWriteView;
/** 保存按钮 */
@property (weak, nonatomic) IBOutlet UIButton *saveBtn;

@property (assign,nonatomic) enum btnTag currentBtnTag;
/** 工单号 */
@property (weak, nonatomic) IBOutlet UILabel *roNoLbl;
/** 接待日期 */
@property (weak, nonatomic) IBOutlet UILabel *createDateLbl;
/** 车牌号 */
@property (weak, nonatomic) IBOutlet UILabel *licenseLbl;
/** 车架号 */
@property (weak, nonatomic) IBOutlet UILabel *vinLbl;
//性别label
@property (weak, nonatomic) IBOutlet UILabel *sexLabel;
//性别按钮
@property (weak, nonatomic) IBOutlet UIButton *sexBtn;
//车型
@property (weak, nonatomic) IBOutlet UILabel *carTypeLabel;
//预约单号
@property (weak, nonatomic) IBOutlet UILabel *yuyueOrderLabel;
//工单状态
@property (weak, nonatomic) IBOutlet UILabel *workStatusLabel;

/** 服务顾问 */
@property (weak, nonatomic) IBOutlet UIButton *serviceAdviserBtn;
/** 工单类型 */
@property (weak, nonatomic) IBOutlet UIButton *jobSheetTypeBtn;
/** 维修分类 */
@property (weak, nonatomic) IBOutlet UIButton *repairTypeBtn;

/** 车主编号 */
@property (strong, nonatomic) NSString *ownerNo;
/** 车主姓名 */
@property (weak, nonatomic) IBOutlet UITextField *carOwnerNameTxt;
/** 联系人姓名 */
@property (weak, nonatomic) IBOutlet UITextField *contactName;
/** 联系人手机 */
@property (weak, nonatomic) IBOutlet UITextField *contactPhone;

@property (weak, nonatomic) IBOutlet UIButton *labourPriceBtn;

/** 里程数 */
@property (weak, nonatomic) IBOutlet UITextField *mileageTxt;

/** 工单备注 */
@property (weak, nonatomic) IBOutlet UITextField *orderRemark;
/** 剩余油量 */
@property (weak, nonatomic) IBOutlet UIButton *leftOverOilBtn;


/** 天窗 */
@property (weak, nonatomic) IBOutlet UIButton *windowBtn;
/** 座椅 */
@property (weak, nonatomic) IBOutlet UIButton *seatBtn;
/** 音响 */
@property (weak, nonatomic) IBOutlet UIButton *soundsBtn;
/** 空调 */
@property (weak, nonatomic) IBOutlet UIButton *airconditioningBtn;
/** 玻璃升降 */
@property (weak, nonatomic) IBOutlet UIButton *glassBtn;
/** 点烟器 */
@property (weak, nonatomic) IBOutlet UIButton *lighterBtn;
/** 防盗器 */
@property (weak, nonatomic) IBOutlet UIButton *carBurglarBtn;
/** 存放功能确认按钮对应值的集合 */
@property(nonatomic,strong) NSDictionary *funtionDicBtns;

/** 眼镜 */
@property (weak, nonatomic) IBOutlet UIButton *glassesBtn;
/** 备胎 */
@property (weak, nonatomic) IBOutlet UIButton *backupTireBtn;
/** 备胎 */
@property (weak, nonatomic) IBOutlet UIButton *toolPackageBtn;
/** 千斤顶 */
@property (weak, nonatomic) IBOutlet UIButton *jackBtn;
/** 警示牌 */
@property (weak, nonatomic) IBOutlet UIButton *warningBoardBtn;
/** 灭火器 */
@property (weak, nonatomic) IBOutlet UIButton *fireExtinguisherBtn;
/** 香烟 */
@property (weak, nonatomic) IBOutlet UIButton *cigaretteBtn;
/** 香烟说明 */
@property (weak, nonatomic) IBOutlet UITextField *cigaretteRemarkTxt;
/** 酒 */
@property (weak, nonatomic) IBOutlet UIButton *beerBtn;
/** 酒说明 */
@property (weak, nonatomic) IBOutlet UITextField *beerRemarkTxt;
/** 现金 */
@property (weak, nonatomic) IBOutlet UIButton *cashBtn;
/** 现金说明 */
@property (weak, nonatomic) IBOutlet UITextField *cashRemarkTxt;
/** 存放物品确认按钮对应值的集合 */
@property(nonatomic,strong) NSDictionary *goodsDicBtns;

/** 存放油量下拉数据 */
@property(nonatomic,strong)NSDictionary *oilDic;
@property(nonatomic,strong)NSDictionary *oilCodeDic;
@property(nonatomic,strong)NSArray *oilNamesArr;
@property (weak, nonatomic) IBOutlet UIButton *oilBtn;

/** 标准工时 */
@property(nonatomic,weak)UITextField *stdWorkHourTxt;
/** 工时费 */
@property(nonatomic,weak)UITextField *workHourChargeTxt;
/** 零件费 */
@property(nonatomic,weak)UITextField *partChargeTxt;
/** 附加项目费 */
@property(nonatomic,weak)UITextField *attachChargeTxt;
/** 保修费用 */
@property(nonatomic,weak)UITextField *repairChargeTxt;
/** 首保费用 */
@property(nonatomic,weak)UITextField *firstRepairChargeTxt;
/** 附加项目费折扣 */
@property(nonatomic,weak)UITextField *attachChargeDiscountTxt;
/** 预交款 */
@property(nonatomic,weak)UITextField *beforPayTxt;
/** 工费折扣 */
@property(nonatomic,weak)UITextField *workHourDiscountTxt;
/** 零件折扣 */
@property(nonatomic,weak)UITextField *partDiscountTxt;
/** 结算金额 */
@property(nonatomic,weak)UITextField *amountTxt;
/** 总金额 */
@property(nonatomic,weak)UITextField *totalAmountTxt;
/** 预交车时间 */
@property(nonatomic,weak)UIButton *sumitCarDateBtn;
/** 优惠模式 */
@property(nonatomic,weak)UIButton *discountModeBtn;


/** 是否洗车 */
@property (weak, nonatomic) UIButton *washCarBtn;
/** 在店等待 */
@property (weak, nonatomic) UIButton *waitBtn;
/** 旧件带走 */
@property (weak, nonatomic) UIButton *takeOldPartBtn;

/** 服务顾问数据列表 */
@property(nonatomic,strong)NSMutableArray *serviceAdviserArr;
@property(nonatomic,strong)NSMutableDictionary *serviceAdviserDic;
@property(nonatomic,strong)NSMutableDictionary *serviceAdviserCodeDic;
/** 性别数据列表 */
@property(nonatomic,strong)NSMutableArray *sexArr;
@property(nonatomic,strong)NSMutableDictionary *sexDic;
@property(nonatomic,strong)NSMutableDictionary *sexCodeDic;
/** 工单类型数据列表 */
@property(nonatomic,strong) NSMutableArray *jobsheetTypeArr;
@property(nonatomic,strong)NSMutableDictionary *jobsheetTypeDic;
@property(nonatomic,strong)NSMutableDictionary *jobsheetTypeCodeDic;

/** 维修分类数据列表 */
@property(nonatomic,strong)NSMutableArray *repairTypeArr;
@property(nonatomic,strong)NSMutableDictionary *repairTypeDic;
@property(nonatomic,strong)NSMutableDictionary *repairTypeCodeDic;

//弹出修改视图
@property(nonatomic,strong)mm_repairItemModifyViewController *repairItemModifyIns;
@property(nonatomic,strong)mm_partModifyViewController *partModifyIns;
@property(nonatomic,strong)mm_otherChargeViewController *otherModifyIns;

@property(nonatomic,strong)CustomizedViewController * customVC;//自定义维修项目

/** 保修费用 */
@property(nonatomic,assign)double repairCharge;
/** 首保费用 */
@property(nonatomic,assign)double firstRepairCharge;

/** 优惠模式列表 */
@property(nonatomic,strong)NSMutableArray *discountNameArr;
@property(nonatomic,strong)NSMutableDictionary *discountModeDic;
@property(nonatomic,strong)NSMutableDictionary *discountModeCodeDic;
/** 选中的优惠模式 */
@property(nonatomic,strong)DiscountItem *selectedDiscount;

/** 工时单价 */
@property(nonatomic,strong)NSMutableArray *labourPrices;
@property(nonatomic,strong)NSString *labourPrice;

/** 选项卡标签页 */
@property(nonatomic,strong)UIView *currentSubView;
@property(nonatomic,assign)CGRect cardTabFrame;
@property(nonatomic,strong)subView1ForGetJobSheet *subView1;
@property(nonatomic,strong)subView2ForGetJobSheet *subView2;
@property(nonatomic,strong)subView3ForGetJobSheet *subView3;

/** 选项卡标签按钮 */
@property(nonatomic,weak)UIButton *tabcardRepairProjectBtn;
@property(nonatomic,weak)UIButton *tabcardRepairPartListBtn;
@property(nonatomic,weak)UIButton *tabcardRepairAttachBtn;

/** 当前正在编辑的文本框 */
@property(nonatomic,strong)UITextField *currentEditingTxt;

/** 最后一次来厂里程（从车辆信息获取） */
@property(nonatomic,assign)double lastMileage;

@property(nonatomic,strong)NSDateFormatter *dateFormatter;


@property(nonatomic,strong)NSString*IS_WINDOW;//是否天窗故障
@property(nonatomic,strong)NSString*IS_CHAIR;//是否座椅故障
@property(nonatomic,strong)NSString*IS_SOUND;//是否音响故障
@property(nonatomic,strong)NSString*IS_AIR;//是否空调故障
//    12781001
@property(nonatomic,strong)NSString*IS_GLASS;//是否玻璃升降故障
@property(nonatomic,strong)NSString*IS_SMOKE;//是否点烟器故障
@property(nonatomic,strong)NSString*IS_SAFE;//是否防盗器故障
@property(nonatomic,strong)NSString*HAS_GLASS;//是否有眼镜
@property(nonatomic,strong)NSString*HAS_BACK;//是否有备胎
@property(nonatomic,strong)NSString*HAS_TOOL;//是否有工具包
@property(nonatomic,strong)NSString*HAS_LIFT;//是否有千斤顶
@property(nonatomic,strong)NSString*HAS_WARN;//是否有警示牌
@property(nonatomic,strong)NSString*HAS_EXTINGUISH;//是否有灭火器
@property(nonatomic,strong)NSString*SPCICAL_DEC;//特别说明


@property(nonatomic,strong)ServiceActiveView * serviceActive;
@property(nonatomic,strong)ReasonView * reasonView;
@property(nonatomic,strong)NSArray * reasonArr;
@property(nonatomic,strong)NSMutableArray * reasonNameArr;
@property(nonatomic,strong)NSMutableArray * reasonCodeArr;
@end

@implementation getJobSheetViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.reasonArr = [self readershuDICimform][@"ACTIVITY_REFUSE_REASON_CODE_LIST"];
    if (self.reasonArr.count>0) {
        for (NSDictionary * dic in self.reasonArr) {
            [self.reasonNameArr addObject:dic[@"NAME"]];
            [self.reasonCodeArr addObject:dic[@"CODE"]];
        }
    }
    
    
    [self.scrollView setContentSize:CGSizeMake(self.scrollView.frame.size.width, 1600.0f)];
    
 

    
    //缺陷列表
    [self createSubViewForPicRemarks];
    
    //用户签名
    UIView*writeView=[[UIView alloc]initWithFrame:CGRectMake(self.scrollView.mj_x,840, self.scrollView.mj_w-2*self.scrollView.mj_x, 50)];

    
    [self.scrollView addSubview:writeView];
    
    UILabel*customerWriteLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 0,100, writeView.mj_h)];
    customerWriteLabel.font=[UIFont boldSystemFontOfSize:20];
    customerWriteLabel.textColor=[UIColor redColor];
    [writeView addSubview:customerWriteLabel];
    customerWriteLabel.text=@"客户签署:";
    
    UIImageView*customerWriteView=[[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(customerWriteLabel.frame)+10, 0,100, writeView.mj_h)];
    [writeView addSubview:customerWriteView];
    self.customerWriteView=customerWriteView;
    customerWriteView.userInteractionEnabled=YES;
    UITapGestureRecognizer*tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickCustomerWrite)];
    [customerWriteView addGestureRecognizer:tap];
    
    //维修项目、零件、附加 标签页按钮
    [self setupTabcarPageButtons];
    
    //维修项目、零件、附加工具按钮
    [self setupTabcardButtons];

    //维修项目、零件、附加项目列表
    [self createSubViews];
    
    [self createLastControls];
    
    //多客户结算按钮创建
//    [self initTheJobSheetTypeBtn];
    
    //功能确认按钮集合的初始化
    [self setupFuncitonalButtons];
    
//    [self createPaiGongAndDaYinBtn];
    
    [self createRemarksOnOutCheckBtn];
    
    [self createCompleteDateBtn];
    
    //创建状态按钮
    [self createStateButton];
    
    [self.scrollView setContentSize:CGSizeMake(self.scrollView.frame.size.width, CGRectGetMaxY(self.takeOldPartBtn.frame)+10)];
    
    //绑定数据
    [self setUpValForAllPlaceViewControls];
    
    self.contactPhone.delegate = self;
    
    [self addAllObserver];
    
    //如果不是新增需要计算
    if (self.optType != operationTypeAdd) {
        [self computeTheValForJobSheet];
    }
    
    //如果是查看模式设置控件不可编辑
    [self setControlDisableIfViewOperation];
    
    //设置是否可以修改 除了待派工状态下 其他都不能修改
    if (!([self.workStatusLabel.text isEqualToString:@"待派工"]||!self.workStatusLabel.text.length)) {
        [self setNotModify];
    }
//    self.serviceActive = [[ServiceActiveView alloc]initWithFrame:CGRectMake(52, 84, 900, 680)];
//    _serviceActive.delegate = self;
//    _serviceActive.vin = self.vinLbl.text;
//    [self.view addSubview:_serviceActive];
}
-(void)setNotModify{
    self.sexBtn.enabled=NO;
    self.contactName.enabled=NO;
    self.contactPhone.enabled=NO;
    self.carOwnerNameTxt.enabled=NO;
    self.jobSheetTypeBtn.enabled=NO;
    self.repairTypeBtn.enabled=NO;
    self.serviceAdviserBtn.enabled=NO;
    self.labourPriceBtn.enabled=NO;
    self.mileageTxt.enabled=NO;
    self.leftOverOilBtn.enabled=NO;
    self.orderRemark.enabled=NO;
    self.addBtn.hidden=YES;
    self.modifyBtn.hidden=YES;
    self.repairGroupBtn.hidden = YES;
    self.customizedBtn.hidden = YES;
    self.saveBtn.hidden=YES;
    self.washCarBtn.enabled=NO;
    self.waitBtn.enabled=NO;
    self.takeOldPartBtn.enabled=NO;
    self.customerWriteView.userInteractionEnabled=NO;
    self.windowBtn.enabled=NO;
    self.seatBtn.enabled=NO;
    self.soundsBtn.enabled=NO;
    self.airconditioningBtn.enabled=NO;
    self.glassBtn.enabled=NO;
    self.lighterBtn.enabled=NO;
    self.carBurglarBtn.enabled=NO;
    self.glassesBtn.enabled=NO;
    self.backupTireBtn.enabled=NO;
    self.toolPackageBtn.enabled=NO;
    self.jackBtn.enabled=NO;
    self.warningBoardBtn.enabled=NO;
    self.fireExtinguisherBtn.enabled=NO;
    self.picRemarkBtn.enabled=NO;
    specialTipsTextView.userInteractionEnabled=NO;
    self.sumitCarDateBtn.enabled=NO;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
    //每当视图即将出现的时候，刷新数据
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    modelIns.nRowForResults = -1;
    modelIns.nRowForIndicationList = -1;
    modelIns.nRowForRepairItemList = -1;
    modelIns.nRowForPartList = -1;
    modelIns.nRowForOtherChargeList = -1;
    
//    [self invokeRequestForMileMaxInCarThrough];
}

/** 如果是查看模式设置控件不可编辑 */
-(void)setControlDisableIfViewOperation{
    if (self.optType == operationTypeView) {
        self.saveBtn.enabled = false;
        for (UIView *subView in self.scrollView.subviews) {
            if (subView == self.picRemarkBtn || subView == self.tabcardRepairProjectBtn|| subView == self.tabcardRepairPartListBtn|| subView == self.tabcardRepairAttachBtn) {
                continue;
            }
            if ([subView isKindOfClass:[UIButton class]]) {
                ((UIButton *)subView).enabled = false;
            }else if ([subView isKindOfClass:[UITextField class]]){
                ((UITextField *)subView).enabled = false;
            }
        }//end for
        specialTipsTextView.editable = false;
    }
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(IBAction)backBtn:(id)sender
{
    if (self.optType == operationTypeView) {
        if (self.returnBack) {
            self.returnBack();
        }
        [self.navigationController popViewControllerAnimated:YES];
        
        return;
    }
    _alerVeiwForSaveJobSheetByBackBtn = [[UIAlertView alloc] initWithTitle:@"是否保存作业单？" message:nil delegate:self cancelButtonTitle:@"保存" otherButtonTitles:@"放弃", nil];
    [_alerVeiwForSaveJobSheetByBackBtn show];

}

-(IBAction)homeBtn:(id)sender{
    if (self.optType == operationTypeView) {
        if (self.returnBack) {
            self.returnBack();
        }
        [self.navigationController popViewControllerAnimated:YES];
        return;
    }
    _alerVeiwForSaveJobSheetByHomeBtn = [[UIAlertView alloc] initWithTitle:@"是否保存作业单？" message:nil delegate:self cancelButtonTitle:@"保存" otherButtonTitles:@"放弃", nil];
    [_alerVeiwForSaveJobSheetByHomeBtn show];
    
}

- (IBAction)picBtnSelect:(id)sender {
    picRecodeViewController *picVcon = [[picRecodeViewController alloc] initWithNibName:@"picRecodeViewController" bundle:nil];
    picVcon.canEdit = self.optType == operationTypeView ? NO : YES;
    picVcon.delegate = self;
    [self.navigationController pushViewController:picVcon animated:YES];
}

#pragma mark - 创建选项卡按钮

-(void)setupTabcarPageButtons{
    CGFloat btnX = 20;
    CGFloat btnY = 900;
    CGFloat btnW = 80;
    CGFloat btnH = 40;
    CGFloat margin = 100;
    self.tabcardRepairProjectBtn = [self createTabcardPageBtnWithTitle:@"维修项目" frame:CGRectMake(btnX, btnY, btnW, btnH) method:@selector(repairItemBtnPressed:)];
    self.tabcardRepairProjectBtn.selected = YES;
    
    btnX += margin;
    self.tabcardRepairPartListBtn = [self createTabcardPageBtnWithTitle:@"零件" frame:CGRectMake(btnX, btnY, btnW, btnH) method:@selector(partListBtnPressed:)];
    
    btnX += margin;
    self.tabcardRepairAttachBtn = [self createTabcardPageBtnWithTitle:@"附加项目" frame:CGRectMake(btnX, btnY, btnW, btnH) method:@selector(otherChargeListBtnPressed:)];
    
    btnX += margin;
   
   
    
    //
}
-(void)clickCustomerWrite{
    WEAKSELF;
    SignViewController*vc=[SignViewController new];
    vc.returnImage = ^(UIImage *img) {
        weakSelf.customerWriteView.image=img;
    };
    [self.navigationController pushViewController:vc animated:YES];
}
-(void)setupTabcardButtons{
    CGFloat y = 913;
    self.addBtn=[self createTabcardButtonWithTitle:@"新增" frame:CGRectMake(560, y, 80, 30) method:@selector(addBtnPressed:)];
  self.modifyBtn=[self createTabcardButtonWithTitle:@"修改" frame:CGRectMake(660, y, 80, 30) method:@selector(modifyBtnPressed:)];
 self.repairGroupBtn= [self createTabcardButtonWithTitle:@"维修组合" frame:CGRectMake(860, y, 90, 30) method:@selector(repairGroupBtnClicked)];
    self.customizedBtn = [self createTabcardButtonWithTitle:@"自定义" frame:CGRectMake(760, y, 90, 30) method:@selector(customizedPressed:)];//870
}

-(UIButton*)createTabcardButtonWithTitle:(NSString *)title frame:(CGRect)frame method:(SEL)method{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = frame;
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"mm_red_btn.png"] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"mm_gray_btn.png"] forState:UIControlStateDisabled];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn addTarget:self action:method forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:btn];
    return btn;
}

-(UIButton *)createTabcardPageBtnWithTitle:(NSString *)title frame:(CGRect)frame method:(SEL)method{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = frame;
    [btn setBackgroundImage:[UIImage imageNamed:@"mm_red_btn.png"] forState:UIControlStateSelected];
    [btn setBackgroundImage:[UIImage imageNamed:@"mm_gray_btn.png"] forState:UIControlStateNormal];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    btn.titleLabel.font = [UIFont systemFontOfSize:15];
    [btn addTarget:self action:method forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:btn];
    return btn;
}

#pragma mark - 维修项目、零件、其他费用视图懒加载

-(void)createSubViews
{
    //维修项目、零件、其他费用的分隔线
    UIView *staticLbl = [[UIView alloc] initWithFrame:CGRectMake(20, 940, 500, 3)];//940+200-50
    staticLbl.backgroundColor = [UIColor redColor];
    [self.scrollView addSubview:staticLbl];
    
    self.cardTabFrame = CGRectMake(21, 950, 948, 198);//950+1+200-50
    self.subView1.hidden = NO;
    self.currentSubView = self.subView1;
}

-(subView1ForGetJobSheet *)subView1{
    if (_subView1 == nil) {
        _subView1 = [[subView1ForGetJobSheet alloc] initWithFrame:self.cardTabFrame];
        _subView1.backgroundColor = [UIColor whiteColor];
        _subView1.hidden = YES;
        _subView1.canEdit = self.optType == operationTypeView ? NO : YES;
        [self.scrollView addSubview:_subView1];
    }
    return _subView1;
}

-(subView2ForGetJobSheet *)subView2{
    if (_subView2 == nil) {
        _subView2 = [[subView2ForGetJobSheet alloc] initWithFrame:self.cardTabFrame];
        _subView2.backgroundColor = [UIColor whiteColor];
        _subView2.hidden = YES;
        _subView2.canEdit = self.optType == operationTypeView ? NO : YES;
        [self.scrollView addSubview:_subView2];
    }
    return _subView2;
}

-(subView3ForGetJobSheet *)subView3{
    if (_subView3 == nil) {
        _subView3 = [[subView3ForGetJobSheet alloc] initWithFrame:self.cardTabFrame];
        _subView3.backgroundColor = [UIColor whiteColor];
        _subView3.hidden = YES;
        _subView3.canEdit = self.optType == operationTypeView ? NO : YES;
        [self.scrollView addSubview:_subView3];
    }
    return _subView3;
}

-(void)updateDataSubView1
{
    [self.subView1 setNeedsDisplay];
    
    //计算价格
    [self computeTheValForJobSheet];
}

-(void)updateDataSubView2
{
    [self.subView2 setNeedsDisplay];
    
    //计算价格
    [self computeTheValForJobSheet];
}

-(void)updateDataSubView3
{
    [self.subView3 setNeedsDisplay];
    
    //计算价格
    [self computeTheValForJobSheet];
}

#pragma mark - //创建显示车辆标记的子视图

-(void)createSubViewForPicRemarks
{
    CGRect rectForPicRemarks = CGRectMake(20, 640, 450, 180);
    CGRect rectForStaticLbl = CGRectMake(480, 640, 80, 30);
    CGRect rectForSpecialTextView = CGRectMake(480+80, 640, 900-540+51, 180);
    
    subViewPicRemarks = [[mm_subViewForPicRemarksInGetJobSheet alloc] initWithFrame:rectForPicRemarks];
    subViewPicRemarks.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:subViewPicRemarks];
    
    UILabel *lbl = [[UILabel alloc] initWithFrame:rectForStaticLbl];
    lbl.backgroundColor = [UIColor clearColor];
    lbl.textColor = [UIColor grayColor];
    lbl.font = [UIFont systemFontOfSize:17];
    lbl.text = @"特别说明:";
    [self.scrollView addSubview:lbl];
    
    specialTipsTextView = [[UITextView alloc] initWithFrame:rectForSpecialTextView];
    specialTipsTextView.layer.borderColor = [UIColor blackColor].CGColor;
    specialTipsTextView.layer.borderWidth = 1.0;
    specialTipsTextView.textColor = [UIColor grayColor];
    specialTipsTextView.font = [UIFont systemFontOfSize:17];
    [self.scrollView addSubview:specialTipsTextView];
}

#pragma mark - 添加本界面中最后边剩余的控件

-(void)createLastControls
{
  
    CGFloat lblW = 100;
    CGFloat lblH = 30;
    CGFloat y = 1168;
//    [self setupLableWithTitle:@"标准工时:" frame:CGRectMake(20, y, lblW, lblH)];
//    y+=margin;
    //CGRectMake(20, y, lblW, lblH)
    [self setupLableWithTitle:@"工时费:" frame:CGRectMake(20, y, lblW, lblH)];
//    y+=margin;
    [self setupLableWithTitle:@"零件费:" frame:CGRectMake(260, y, lblW, lblH)];
//    y+=margin;
    [self setupLableWithTitle:@"附加项目费:" frame:CGRectMake(500, y, lblW, lblH)];
//    y = 1108;
//    [self setupLableWithTitle:@"保修费用:" frame:CGRectMake(260, y, lblW, lblH)];
//    y+=margin;
//    [self setupLableWithTitle:@"首保费用:" frame:CGRectMake(260, y, lblW, lblH)];
//    y+=margin;
//    [self setupLableWithTitle:@"附加折扣:" frame:CGRectMake(260, y, lblW, lblH)];
//    y+=margin;
//    [self setupLableWithTitle:@"预交款:" frame:CGRectMake(260, y, lblW, lblH)];
//    y = 1108;
//    [self setupLableWithTitle:@"工费折扣:" frame:CGRectMake(500, y, lblW, lblH)];
//    y+=margin;
//    [self setupLableWithTitle:@"零件折扣:" frame:CGRectMake(500, y, lblW, lblH)];
//    y+=margin;
//    [self setupLableWithTitle:@"优惠模式:" frame:CGRectMake(500, y, lblW, lblH)];
//    y+=margin;
//    [self setupLableWithTitle:@"结算金额:" frame:CGRectMake(500, y, lblW, lblH)];
//    y = 1108+margin*2;
//    [self setupLableWithTitle:@"预定交车日:" frame:CGRectMake(740, y, lblW, lblH)];
//    y+=margin;
    [self setupLableWithTitle:@"总金额:" frame:CGRectMake(740, y, lblW, lblH)];
    
    //创建文本框
    CGFloat txtW = 140;
    CGFloat txtH = 35;
    y = 1168;
//    self.stdWorkHourTxt = [self setupTextFieldWithFrame:CGRectMake(110, y, txtW, txtH) enable:false];
//    y+=margin;
    self.workHourChargeTxt = [self setupTextFieldWithFrame:CGRectMake(110, y, txtW, txtH) enable:false];
//    y+=margin;
    
    self.partChargeTxt = [self setupTextFieldWithFrame:CGRectMake(350, y, txtW, txtH) enable:false];
//    y+=margin;
    self.attachChargeTxt = [self setupTextFieldWithFrame:CGRectMake(590, y, txtW, txtH) enable:false];
//    y = 1108;
//    self.repairChargeTxt = [self setupTextFieldWithFrame:CGRectMake(350, y, txtW, txtH) enable:false];
//    y+=margin;
//    self.firstRepairChargeTxt = [self setupTextFieldWithFrame:CGRectMake(350, y, txtW, txtH) enable:false];
//    y+=margin;
//    self.attachChargeDiscountTxt = [self setupTextFieldWithFrame:CGRectMake(350, y, txtW, txtH) enable:false];
//    y+=margin;
//    self.beforPayTxt = [self setupTextFieldWithFrame:CGRectMake(350, y, txtW, txtH) enable:false];
//    y = 1108;
//    self.workHourDiscountTxt = [self setupTextFieldWithFrame:CGRectMake(590, y, txtW, txtH) enable:false];
//    y+=margin;
//    self.partDiscountTxt = [self setupTextFieldWithFrame:CGRectMake(590, y, txtW, txtH) enable:false];
//    y+=margin;
//    //优惠模式
//    CGRect dropDownBg = CGRectMake(590, y, txtW, txtH);
//    [self setupDropdownBackgroundWithFrame:dropDownBg];
//    self.discountModeBtn = [self setupDrodownBtnWithBgFrame:dropDownBg method:@selector(selectBtnPressed:)];
//    y+=margin;
    //结算金额
//    self.amountTxt = [self setupTextFieldWithFrame:CGRectMake(590, y, txtW, txtH) enable:false];
//    y+=margin;
    //总金额
    self.totalAmountTxt = [self setupTextFieldWithFrame:CGRectMake(830,y, txtW, txtH) enable:false];
    
}

-(UILabel *)setupLableWithTitle:(NSString *)title frame:(CGRect)frame{
    UILabel *lbl = [[UILabel alloc] initWithFrame:frame];
    lbl.text = title;
    lbl.backgroundColor = [UIColor clearColor];
    lbl.textColor = [UIColor grayColor];
    lbl.font = [UIFont systemFontOfSize:14];
    lbl.textAlignment = NSTextAlignmentCenter;
    [self.scrollView addSubview:lbl];
    return lbl;
}

-(UITextField *)setupTextFieldWithFrame:(CGRect)frame enable:(BOOL)enable{
    UITextField *textFieldIns = [[UITextField alloc] initWithFrame:frame];
    textFieldIns.borderStyle = UITextBorderStyleLine;
    textFieldIns.textColor = [UIColor grayColor];
    textFieldIns.font = [UIFont systemFontOfSize:17];
    textFieldIns.enabled = enable;
    if (!enable) {
        textFieldIns.backgroundColor = [UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1];
    }
    [self.scrollView addSubview:textFieldIns];
    return textFieldIns;
}

#pragma mark - 创建状态按钮

-(void)createStateButton
{
    CGFloat y = CGRectGetMaxY(self.totalAmountTxt.frame)+20;
    self.washCarBtn = [self createButtonsWithTitle:@"是否洗车" frame:CGRectMake(20, y, 80, 44)];
    self.waitBtn = [self createButtonsWithTitle:@"在店等待" frame:CGRectMake(110, y, 80, 44)];
    self.takeOldPartBtn = [self createButtonsWithTitle:@"旧件带走" frame:CGRectMake(200, y, 80, 44)];
}

-(UIButton *)createButtonsWithTitle:(NSString *)title frame:(CGRect)frame{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = frame;
    btn.titleLabel.font=HJFont(12);
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"mm_gray_btn.png"] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"mm_red_btn.png"] forState:UIControlStateSelected];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    btn.titleLabel.font = [UIFont systemFontOfSize:17];
    [btn addTarget:self action:@selector(functionalConfirmClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:btn];
    return btn;
}


#pragma mark - 维修项目、零件、附加项目 选项卡按钮回调方法

- (void)repairItemBtnPressed:(UIButton *)sender
{
    [self switchToSubView:self.subView1 repairViewHidden:NO partListViewHidden:YES otherViewHidden:YES viewTag:repairItemBtnTag];
}

- (void)partListBtnPressed:(UIButton *)sender
{
    [self switchToSubView:self.subView2 repairViewHidden:YES partListViewHidden:NO otherViewHidden:YES viewTag:partListBtnTag];
}

- (void)otherChargeListBtnPressed:(UIButton *)sender
{
    [self switchToSubView:self.subView3 repairViewHidden:YES partListViewHidden:YES otherViewHidden:NO viewTag:otherChargeLiatBtnTag];
}


-(void)switchToSubView:(UIView *)view repairViewHidden:(BOOL)rHidden partListViewHidden:(BOOL)pHidden otherViewHidden:(BOOL)oHidden viewTag:(btnTag)tag{
    self.tabcardRepairProjectBtn.selected = !rHidden;
    self.tabcardRepairPartListBtn.selected = !pHidden;
    self.tabcardRepairAttachBtn.selected = !oHidden;
    
    self.subView1.hidden = rHidden;
    self.subView2.hidden = pHidden;
    self.subView3.hidden = oHidden;
    [view setNeedsDisplay];
    self.currentSubView = view;
    //设置标志，用于识别当前的button
    self.currentBtnTag = tag;
}

#pragma mark - 新增 修改 维修组合 按钮点击

/*
 下边的添加按钮跳转界面时，将本界面正在操作的项目传给本界面的二级界面
 */

- (void)addBtnPressed:(UIButton *)sender
{
    double discount = 1;
    if (self.currentSubView == self.subView3)
    {
        _otherModifyIns = [[mm_otherChargeViewController alloc] initWithNibName:@"mm_otherChargeViewController" bundle:nil];
        self.otherModifyIns.newOperation = true;
        if (self.selectedDiscount&&self.selectedDiscount.attachDiscount!=0) {
            discount = self.selectedDiscount.attachDiscount;
        }
        _otherModifyIns.discount = discount;
        [self presentPopupViewController:_otherModifyIns animationType:MJPopupViewAnimationFade];
    }else{
        //跳转到该界面的二级界面－新增界面
        MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
        
        //基本信息
        NSDictionary *baseInfoDic = modelIns.dicBaseMessage;
        
        mm_addAndModifyViewController *vcForAddDis = [[mm_addAndModifyViewController alloc] init];
        vcForAddDis.delegate = self;
        vcForAddDis.carType=self.carTypeLabel.text;
        vcForAddDis.carTypeCode=baseInfoDic[@"MODEL"];
        vcForAddDis = [vcForAddDis initWithNibName:@"mm_addAndModifyViewController" bundle:nil];
        bool isRepairList = true;
        if (self.currentSubView == self.subView2)
        {
            isRepairList = NO;
        }
        if (self.selectedDiscount&&self.selectedDiscount.repairDiscount !=0) {
            discount = self.selectedDiscount.repairDiscount;
        }
        vcForAddDis.repairDiscount = discount;
        if (self.selectedDiscount&&self.selectedDiscount.partDiscount !=0) {
            discount = self.selectedDiscount.partDiscount;
        }
        vcForAddDis.partDiscount = discount;
        vcForAddDis.isRepairPage = isRepairList;
        vcForAddDis.labourPrice = self.labourPrice;
        vcForAddDis.jobSheetLabourPrice = self.labourPriceBtn.titleLabel.text;
        [self.navigationController pushViewController:vcForAddDis animated:YES];

    }
}

- (void)modifyBtnPressed:(UIButton *)sender
{
//    NSLog(@"modifyBtnPressed !!!");
    
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    double discount = 1;
    //弹出修改界面
    if (self.currentSubView == self.subView1 && modelIns.nRowForRepairItemList != -1)
    {

        NSDictionary * repairDic = modelIns.repairProjects[modelIns.nRowForRepairItemList];
        
        if (repairDic[@"ACTIVITY_CODE"]) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"服务活动下的维修项目不可修改" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        
            [alert show];
            return;
        }
    if(self.selectedDiscount&&self.selectedDiscount.repairDiscount != 0) {
            discount = self.selectedDiscount.repairDiscount;
        }
        _repairItemModifyIns = [[mm_repairItemModifyViewController alloc] initWithNibName:@"mm_repairItemModifyViewController" bundle:nil];
        _repairItemModifyIns.discount = discount;
        _repairItemModifyIns.labourPrice = self.labourPrice;
        _repairItemModifyIns.jobSheetLabourPrice = self.labourPriceBtn.titleLabel.text;
        [self presentPopupViewController:_repairItemModifyIns animationType:MJPopupViewAnimationFade];
    }
    else if (self.currentSubView == self.subView2 && modelIns.nRowForPartList != -1)
    {
        NSDictionary * repairDic = modelIns.partList[modelIns.nRowForPartList];
        
        if (repairDic[@"ACTIVITY_CODE"]) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"服务活动下的零件不可修改" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            
            [alert show];
            return;
        }

        if (self.selectedDiscount&&self.selectedDiscount.partDiscount != 0) {
            discount = self.selectedDiscount.partDiscount;
        }
        _partModifyIns = [[mm_partModifyViewController alloc] initWithNibName:@"mm_partModifyViewController" bundle:nil];
        _partModifyIns.discount = discount;
        [self presentPopupViewController:_partModifyIns animationType:MJPopupViewAnimationFade];
    }
    else if (self.currentSubView == self.subView3 && modelIns.nRowForOtherChargeList != -1)
    {
        if (self.selectedDiscount&&self.selectedDiscount.attachDiscount != 0) {
            discount = self.selectedDiscount.attachDiscount;
        }
        _otherModifyIns = [[mm_otherChargeViewController alloc] initWithNibName:@"mm_otherChargeViewController" bundle:nil];
        self.otherModifyIns.discount = discount;
        self.otherModifyIns.newOperation = false;
        [self presentPopupViewController:_otherModifyIns animationType:MJPopupViewAnimationFade];
    }
    else
    {
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"请选择一行数据" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alerVeiw show];
        return;
    }
}
/**自定义按钮点击*/
-(void)customizedPressed:(UIButton *)sender{
    if (self.currentSubView != self.subView1){
        [self switchToSubView:self.subView1 repairViewHidden:NO partListViewHidden:YES otherViewHidden:YES viewTag:repairItemBtnTag];
    }
    _customVC = [[CustomizedViewController alloc]init];
    _customizedShow = YES;
    _customVC.delegate = self;
     [self presentPopupViewController:_customVC animationType:MJPopupViewAnimationFade];
}
-(void)ClickCanelBtn{
    [self dismissPopupViewControllerWithanimationType:MJPopupViewAnimationFade];
}
-(void)ClickMakeSureBtn{
       [self dismissPopupViewControllerWithanimationType:MJPopupViewAnimationFade];
}
/** 维修组合按钮点击 */
-(void)repairGroupBtnClicked{
//    mm_jobItemGroupViewController *vc = [[mm_jobItemGroupViewController alloc]init];
//    vc.delegate = self;
//    if (self.selectedDiscount) {
//        vc.repairDiscount = self.selectedDiscount.repairDiscount;
//        vc.partDiscount = self.selectedDiscount.partDiscount;
//    }else{
//        vc.repairDiscount = 1;
//        vc.partDiscount = 1;
//    }
//    [self.navigationController pushViewController:vc animated:YES];
    HJRepairGroupViewController*vc=[HJRepairGroupViewController new];
    vc.returnRepairtGroup = ^(NSArray *repairtAry, NSArray *partsAry) {
         MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
        for (HJRepairtGroupTM_PACKAGE_LABOURModel*TM_PACKAGE_LABOURModel in repairtAry) {
            NSMutableDictionary *seletedData = TM_PACKAGE_LABOURModel.mj_keyValues;
           
            //    ;
            
//            NSString *chargeDiffVal = self.chargeDiff[charDiffBtn.titleLabel.text];
//            if (!chargeDiffVal) {
//                chargeDiffVal = @"";
//            }
//             [seletedData setObject:chargeDiffVal forKey:@"CHARGE_PARTITION_CODE"];//收费区分
            
           
           
            [seletedData setObject:@"" forKey:@"ITEM_ID"];//id
            [seletedData setObject:@"A" forKey:@"STATUS"];//状态
//            [seletedData setObject:@(self.discount) forKey:@"DISCOUNT"];//折扣
           
//            NSString *repairTypeCode = self.repairTypeDic[self.repairTypeBtn.titleLabel.text];
//            seletedData[@"REPAIR_TYPE_CODE"] = repairTypeCode;//维修分类
//            [seletedData setObject:self.labourPriceBtn.currentTitle forKey:@"LABOUR_PRICE"];//工时单价
//            [seletedData setObject:workHourChargeTxt.text forKey:@"LABOUR_AMOUNT"];//工时费
            [modelIns.repairProjects addObject:seletedData];
        }
//
        //更新完数据后刷新界面
        [[NSNotificationCenter defaultCenter] postNotificationName:SECOND_REPAIR_ITEM_LIST_MSG_ object:nil];
        
        for (HJRepairtGroupTM_PACKAGE_PARTModel*TM_PACKAGE_PARTModel in partsAry) {
            NSMutableDictionary *seletedData = TM_PACKAGE_PARTModel.mj_keyValues;
    
            [seletedData setObject:@"" forKey:@"ITEM_ID"];//id
            [seletedData setObject:@"A" forKey:@"STATUS"];//状态
            [modelIns.partList addObject:seletedData];
        }
        //更新完数据后刷新界面
        [[NSNotificationCenter defaultCenter] postNotificationName:SECOND_PART_LIST_MSG_ object:nil];
        [self.subView1 freshenViewDis];
        
        [self.subView2 freshenViewDis];
        [self computeTheValForJobSheet];
    };
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - 维修项目、零件、其他费用修改视图dissmiss

-(void)dismissPopupViewControllerWithanimationType:(MJPopupViewAnimation)animationType
{
    BOOL flag = true;
    //保存数据
    if (self.currentSubView == self.subView1)
    {
        if (_customizedShow) {
            _customizedShow = NO;
        }else{
            flag = [self.repairItemModifyIns saveData];
        }
    }
    else if (self.currentSubView == self.subView2)
    {
        flag =[self.partModifyIns saveData];
    }
    else if (self.currentSubView == self.subView3)
    {
        flag = [self.otherModifyIns saveData];
    }
    if (flag) {
        [super dismissPopupViewControllerWithanimationType:animationType];
        //刷新数据
        [self.currentSubView setNeedsDisplay];
        
        //计算价格
        [self computeTheValForJobSheet];
        
        MainMenuDataModel *mainModel = [MainMenuDataModel sharedMainMenuDataModel];
        mainModel.nRowForRepairItemList = -1;
        mainModel.nRowForPartList = -1;
        mainModel.nRowForOtherChargeList = -1;
    }
    
}

-(void)switchTomutipleCustomerToAllocate
{
    
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    for (int i = 0; i<[modelIns.arrAllocationList count]; i++)
    {
        if (0 == [[[modelIns.arrAllocationList objectAtIndex:i] objectForKey:MM_CUSTOMER_LIST_KEY_STR_] count])
        {
            NSString *customerIdTmp = [[_arrOriginalDataForDocumentBill objectAtIndex:_nRowDocumentBillSel] objectForKey:@"customerId"];
            NSString *customerNameTmp = [[_arrOriginalDataForDocumentBill objectAtIndex:_nRowDocumentBillSel] objectForKey:@"billDocument"];
            NSString *moneyTmp = [[modelIns.arrAllocationList objectAtIndex:i] objectForKey:MM_ALLOCATION_REPAIR_MONEY_KEY_STR_];
            NSDictionary *dicTmp = [NSDictionary dictionaryWithObjectsAndKeys:
                                    customerIdTmp,@"customerId",
                                    customerNameTmp,@"customerName",
                                    @"100",@"proportion",
                                    moneyTmp,@"repairMoney",
                                    @"1",@"balanceFlag", nil];
            modelIns.arrAllocationList = [NSMutableArray arrayWithArray:modelIns.arrAllocationList];
            NSArray *arrCustomerListTmp = [NSArray arrayWithObjects:dicTmp, nil];
            
            NSMutableDictionary *dicAllocationTmp = [NSMutableDictionary dictionaryWithDictionary:[modelIns.arrAllocationList objectAtIndex:i]];
            [dicAllocationTmp setObject:arrCustomerListTmp forKey:MM_CUSTOMER_LIST_KEY_STR_];
            
            [modelIns.arrAllocationList setObject:dicAllocationTmp atIndexedSubscript:i];
        }
    }
    
    //跳转到多客户分配界面
    mm_multipleCustomerToAllocateViewController *vc = [[mm_multipleCustomerToAllocateViewController alloc] initWithNibName:@"mm_multipleCustomerToAllocateViewController" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView == _alerVeiwForMultipleCustomerToAllocate)
    {
        switch (buttonIndex)
        {
            case 0:
                [self switchTomutipleCustomerToAllocate];
                break;
                
            default:
                break;
        }
    }
    else if (alertView == _alerVeiwForSaveJobSheetByBackBtn)
    {
        switch (buttonIndex)
        {
            case 0:
                //保存
                [self saveBtnPressed:nil];
                break;
            case 1:
                //放弃
                if (self.returnBack) {
                    self.returnBack();
                }
                [self.navigationController popViewControllerAnimated:YES];
                break;
                
            default:
                break;
        }
    }
    else if (alertView == _alerVeiwForSaveJobSheetByHomeBtn)
    {
        switch (buttonIndex)
        {
            case 0:
                //保存
                [self saveBtnPressed:nil];
                break;
            case 1:
                //放弃
                [self.navigationController popToRootViewControllerAnimated:YES];
                break;
                
            default:
                break;
        }
    }
    else if (alertView == _alertViewForMileInputWhenBack)
    {
        switch (buttonIndex)
        {
            case 0:
                //弹出竟警示框提示是否“是否保存作业单！”
                _alerVeiwForSaveJobSheetByBackBtn = [[UIAlertView alloc] initWithTitle:@"是否保存作业单？" message:nil delegate:self cancelButtonTitle:@"保存" otherButtonTitles:@"放弃", nil];
                [_alerVeiwForSaveJobSheetByBackBtn show];
                break;
            case 1:
                break;
                
            default:
                break;
        }
    }
    else if (alertView == _alertViewForMileInputWhenHome)
    {
        switch (buttonIndex)
        {
            case 0:
                //弹出竟警示框提示是否“是否保存作业单！”
                _alerVeiwForSaveJobSheetByHomeBtn = [[UIAlertView alloc] initWithTitle:@"是否保存作业单？" message:nil delegate:self cancelButtonTitle:@"保存" otherButtonTitles:@"放弃", nil];
                [_alerVeiwForSaveJobSheetByHomeBtn show];
                break;
            case 1:
                break;
                
            default:
                break;
        }
    }
}
#pragma mark ---  serviceActiveViewDelegate
-(void)ServiceActiveViewClickMakeSureBtn{
    [self repairAndPartListDataChanged];
    [_serviceActive removeFromSuperview];
}
#pragma mark - 通过由接口获取的数据，设置控件的内容
-(void)setUpValForAllPlaceViewControls
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    //基本信息
    NSDictionary *baseInfoDic = modelIns.dicBaseMessage;
    NSString *createDate = nil;
    NSString *carNo = nil;
    NSString *contactName = nil;
    NSString *contactMobile = nil;
    NSString *adviserName = nil;
    NSString *jobSheetTypeName = nil;
    NSString * sexName=nil;
    NSString*carType=nil;
    
    //服务顾问
    [self serviceAdviserArr];
    
    //性别
    [self sexArr];
    
    //工单类型
    [self jobsheetTypeArr];
    
    NSString*sex =baseInfoDic[@"DELIVERER_GENDER"];
    sex=[NSString stringWithFormat:@"%@",sex];
    sexName=self.sexCodeDic[sex];
     [self.sexBtn setTitle:sexName forState:UIControlStateNormal];//用户性别
    if (self.optType == operationTypeAdd) {//新增
        WEAKSELF;

       
        createDate = self.currentDate;
        carNo = baseInfoDic[@"PLATE_NUMBER"];
        if (!carNo.length) {
            carNo = [baseInfoDic objectForKey:@"LICENSE"];
        }
        contactName = baseInfoDic[@"CONTACTOR_NAME"];
        if (!contactName.length) {
            contactName = baseInfoDic[@"OWNER_NAME"];
        }
        contactMobile = baseInfoDic[@"CONTACTOR_MOBILE"];
        if (!contactMobile.length) {
            contactMobile=baseInfoDic[@"MOBILE"];
        }
       
        //设置服务顾问默认为当前登录人
        adviserName = [[NSUserDefaults standardUserDefaults]objectForKey:@"USER_NAME"];
        
        //设置工单类型默认为维修
        jobSheetTypeName = self.jobsheetTypeCodeDic[@"12531001"];//获取工单类型为维修的名称
        
        
            self.serviceActive = [[ServiceActiveView alloc]initWithFrame:CGRectMake(52, 84, 900, 680)];
            _serviceActive.delegate = self;
            _serviceActive.vin = baseInfoDic[@"VIN"];
            [self.view addSubview:_serviceActive];
        _serviceActive.hidden = YES;
        
   
        
        NSDictionary *param1 = @{@"VIN":baseInfoDic[@"VIN"]};
        [MyAFNetWorkManager postWithParam:param1 andAction:@"QUERY_ACTIVITY_FOR_PAD" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
            [SVProgressHUD dismiss];
            if (error) {
                [SVProgressHUD showErrorWithStatus:@"获取数据失败"];
                return;
            }else{
                NSArray *TT_ACTIVITY =obj[@"TT_ACTIVITY"];
                if ([obj[@"SUCCESS"] integerValue] == 1 && TT_ACTIVITY.count>0) {
                    
                    _serviceActive.hidden = NO;
                    _serviceActive.dataDic  = obj;
                }

            }
        }];
        
        //初始化订单时需要去服务器判断是否进厂
        NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
        NSString*LICENSE=baseInfoDic[@"LICENSE"];
        NSDictionary *param = @{@"VIN":baseInfoDic[@"VIN"],
                                @"LICENSE":LICENSE.length?LICENSE:@"",
                                @"ENTITY_CODE":[user objectForKey:@"ENTITY_CODE"],
                                @"CONTACTOR_MOBILE":contactMobile.length?contactMobile:@"",
                                };
        [MyAFNetWorkManager postWithParam:param andAction:@"ORDER_NOT_CONMMING_PAD" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
            [SVProgressHUD dismiss];
            if (error) {
                [SVProgressHUD showErrorWithStatus:@"获取数据失败"];
                return;
            }else{
                NSArray*ary=[HJNotConmmingPadModel mj_objectArrayWithKeyValuesArray:obj[@"ORDER_NOT_CONMMING_LIST"]];
                if (ary.count) {
                    HJMakeAppointmentSelectView*makeAppointmentSelectView=[[HJMakeAppointmentSelectView alloc]init];
                    makeAppointmentSelectView.delegate=self;
                    [weakSelf.view addSubview:makeAppointmentSelectView];
                    [makeAppointmentSelectView mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.left.top.right.bottom.mas_equalTo(weakSelf.view);
                    }];
                    makeAppointmentSelectView.dataAry=ary;
                }
            }
        }];
#pragma mark -- 初始化工单
    
    }else{
        self.roNoLbl.text = [baseInfoDic objectForKey:@"RO_NO"];
        createDate = [baseInfoDic objectForKey:@"RO_CREATE_DATE"];
        carNo = [baseInfoDic objectForKey:@"LICENSE"];
        contactName = baseInfoDic[@"DELIVERER"];//联系人
        contactMobile = baseInfoDic[@"DELIVERER_MOBILE"];
        
        id code = baseInfoDic[@"SERVICE_ADVISOR"];
        adviserName =self.serviceAdviserCodeDic[code];
        
        //设置工单类型
        code = [baseInfoDic[@"RO_TYPE"]stringValue];
        jobSheetTypeName = self.jobsheetTypeCodeDic[code];
        
        //维修分类
        [self repairTypeArr];
        code = baseInfoDic[@"REPAIR_TYPE_CODE"];
        [self.repairTypeBtn setTitle:self.repairTypeCodeDic[code] forState:UIControlStateNormal];
        
        //工时单价
        [self.labourPriceBtn setTitle:[baseInfoDic[@"LABOUR_PRICE"]stringValue] forState:UIControlStateNormal];
        
        //里程
        self.mileageTxt.text = [baseInfoDic[@"IN_MILEAGE"]stringValue];
        self.orderRemark.text = baseInfoDic[@"REMARK"];
        
        //油量
        code = [baseInfoDic[@"OIL_REMAIN"]stringValue];
        [self.oilBtn setTitle:self.oilCodeDic[code] forState:UIControlStateNormal];
        
//        //功能确认
//        [self initFunctionBtnWithStr:baseInfoDic[@"TROUBLE_CONFIRM"]];

        
        //特别说明
        specialTipsTextView.text = baseInfoDic[@"ITEMS_SPECIAL_DESC"];
        
        //是否洗车
        code = [baseInfoDic[@"IS_WASH"]stringValue];
        if ([code isEqualToString:@"12781001"]) {
            self.washCarBtn.selected = YES;
        }

        code = [baseInfoDic[@"IS_TAKE_PART_OLD"]stringValue];
        if ([code isEqualToString:@"12781001"]) {
            self.takeOldPartBtn.selected = YES;
        }
        
        code = [baseInfoDic[@"IS_CUSTOMER_IN_ASC"]stringValue];
        if ([code isEqualToString:@"12781001"]) {
            self.waitBtn.selected = YES;
        }
        
        //优惠模式
        code = baseInfoDic[@"DISCOUNT_MODE_CODE"];
        [self discountNameArr];
        code = self.discountModeCodeDic[code];//优惠name
        self.selectedDiscount = self.discountModeDic[code];
        [self.discountModeBtn setTitle:code forState:UIControlStateNormal];
        
        [self.sumitCarDateBtn setTitle:baseInfoDic[@"END_TIME_SUPPOSED"] forState:UIControlStateNormal];//预定交车日期
        
        //工单状态
        NSString*number=[NSString stringWithFormat:@"%zd",[baseInfoDic[@"RO_DETAIL_STATUS"] integerValue]];
        self.workStatusLabel.text= [self getGongdanzhuangtai:number];
        //设置环车数据
        HJRepairOrderInfoCheckOrderModel*repairOrderInfoCheckOrderModel=self.repairOrderInfoModel.TT_RO_CHECK_ORDER[0];
        //天窗
        if ([repairOrderInfoCheckOrderModel.IS_WINDOW integerValue]==12781001) {
            [self functionalConfirmClicked:self.windowBtn];
        }
        //座椅IS_CHAIR
        if ([repairOrderInfoCheckOrderModel.IS_CHAIR integerValue]==12781001) {
            [self functionalConfirmClicked:self.seatBtn];
        }
        //音响
        if ([repairOrderInfoCheckOrderModel.IS_SOUND integerValue]==12781001) {
            [self functionalConfirmClicked:self.soundsBtn];
        }
        //空调
        if ([repairOrderInfoCheckOrderModel.IS_AIR integerValue]==12781001) {
            [self functionalConfirmClicked:self.airconditioningBtn];
        }
        //玻璃升降
        if ([repairOrderInfoCheckOrderModel.IS_GLASS integerValue]==12781001) {
            [self functionalConfirmClicked:self.glassBtn];
        }
        //点烟器
        if ([repairOrderInfoCheckOrderModel.IS_SMOKE integerValue]==12781001) {
            [self functionalConfirmClicked:self.lighterBtn];
        }
        //防盗器
        if ([repairOrderInfoCheckOrderModel.IS_SAFE integerValue]==12781001) {
            [self functionalConfirmClicked:self.carBurglarBtn];
        }
        //眼镜
        if ([repairOrderInfoCheckOrderModel.HAS_GLASS integerValue]==12781001) {
            [self goodsConfirmBtnClicked:self.glassesBtn];
        }
        //备胎
        if ([repairOrderInfoCheckOrderModel.HAS_BACK integerValue]==12781001) {
            [self goodsConfirmBtnClicked:self.backupTireBtn];
        }
        //工具包
        if ([repairOrderInfoCheckOrderModel.HAS_TOOL integerValue]==12781001) {
            [self goodsConfirmBtnClicked:self.toolPackageBtn];
        }
        //千斤顶
        if ([repairOrderInfoCheckOrderModel.HAS_LIFT integerValue]==12781001) {
            [self goodsConfirmBtnClicked:self.jackBtn];
        }
        //警示牌
        if ([repairOrderInfoCheckOrderModel.HAS_WARN integerValue]==12781001) {
            [self goodsConfirmBtnClicked:self.warningBoardBtn];
        }
        //灭火器
        if ([repairOrderInfoCheckOrderModel.HAS_EXTINGUISH integerValue]==12781001) {
            [self goodsConfirmBtnClicked:self.fireExtinguisherBtn];
        }
        
        //添加签名
         NSString *url = [NSString stringWithFormat:@"http://%@/INFO_DMS_WEB/download?FILE_ID=%@&FILE_OWNER=%@&APP_ID=AttachmentPhoto",[[NSUserDefaults standardUserDefaults]objectForKey:@"ip"],repairOrderInfoCheckOrderModel.CUSTOMER_SIGN_ID,repairOrderInfoCheckOrderModel.ENTITY_CODE];
        WEAKSELF;
        [self.customerWriteView sd_setImageWithURL:[NSURL URLWithString:url] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
}];
       
        
       
    }
    
    //车型
    NSArray*carTypeAry=[self readershuDICimform][@"CONFIG"];
    for (NSDictionary*dict in carTypeAry) {
        if ([dict[@"MODEL_CODE"] isEqualToString:baseInfoDic[@"MODEL"]]) {
            self.carTypeLabel.text=dict[@"CONFIG_NAME"];
            break;
        }
    }
    
    self.yuyueOrderLabel.text=[baseInfoDic objectForKey:@"BOOKING_ORDER_NO"];
    self.licenseLbl.text = carNo;
    self.vinLbl.text = [baseInfoDic objectForKey:@"VIN"];
    self.carOwnerNameTxt.text = [baseInfoDic objectForKey:@"OWNER_NAME"];
    self.ownerNo = [baseInfoDic objectForKey:@"OWNER_NO"];
    self.labourPrice = [[baseInfoDic objectForKey:@"LABOURPRICE"]stringValue];
    [self.jobSheetTypeBtn setTitle:jobSheetTypeName forState:UIControlStateNormal];//工单类型
    
    [self.serviceAdviserBtn setTitle:adviserName forState:UIControlStateNormal];//服务顾问
    self.contactName.text = contactName;//联系人
    self.contactPhone.text = contactMobile;//联系人手机
    self.createDateLbl.text = createDate;//接待日期
   
    self.beforPayTxt.text = [[baseInfoDic objectForKey:@"PRE_PAY"]stringValue];
    //最后一次进厂里程
    self.lastMileage = baseInfoDic[@"CURRENT_MILEAGE"]? [baseInfoDic[@"CURRENT_MILEAGE"]doubleValue]: 0;

}

///** 初始化功能确认 */
//-(void)initFunctionBtnWithStr:(NSString *)str{
//    if (str && str.length>0) {
//        NSArray *arr = [str componentsSeparatedByString:@","];
//        for (NSString *val in arr) {
//            UIButton *btn = self.funtionDicBtns[val];
//            btn.selected = YES;
//        }
//    }
//}

-(NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

-(NSDictionary *)goodsDicBtns{
    _goodsDicBtns = @{
                      @"眼镜":self.glassesBtn,
                      @"备胎":self.backupTireBtn,
                      @"工具包":self.toolPackageBtn,
                      @"千斤顶":self.jackBtn,
                      @"警示牌":self.warningBoardBtn,
                      @"灭火器":self.fireExtinguisherBtn
                      };
    return _goodsDicBtns;
}

#pragma mark - 设置选择按钮的回调方法
- (IBAction)selectSex:(id)sender {
     [self createThePopViewControl:sender];
     contentCon.list = self.sexArr;
     [contentCon.myTableView reloadData];
}
-(void)createThePopViewControl:(UIButton *)sender
{
    if (!contentCon)
    {
        contentCon=[[popContentViewController alloc] initWithNibName:@"popContentViewController" bundle:nil];
    }
    
    contentCon.delegate = self;
    contentCon.btnSender=sender;
    
    self.popCon = [[UIPopoverController alloc] initWithContentViewController:contentCon];
    [DDPopoverBackgroundView setTintColor:[UIColor colorWithRed:234 green:248 blue:222 alpha:0.9]];
    [DDPopoverBackgroundView setArrowBase:30.0];//箭头
    [DDPopoverBackgroundView setArrowHeight:15.0];
    [DDPopoverBackgroundView setContentInset:1.0];
    
    [self.popCon setPopoverBackgroundViewClass:[DDPopoverBackgroundView class]];
    [self.popCon setPopoverContentSize:CGSizeMake(sender.frame.size.width, 280)];
    
    [self.popCon presentPopoverFromRect:CGRectMake(40, 15, 70, 20) inView:sender permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}

-(IBAction)selectBtnPressed:(UIButton *)sender
{
    //调用get数据接口，获取数据
    
    /*
     btn tag 对照表：
     获取估价人：104；服务类型：105；维修种类：106；单据对象：108；发票类型：109
     */
    [self createThePopViewControl:sender];
    if (sender == self.serviceAdviserBtn)//服务顾问
    {
        contentCon.list = self.serviceAdviserArr;
    }
    else if (sender == self.jobSheetTypeBtn)//工单类型
    {
        contentCon.list = self.jobsheetTypeArr;
    }
    else if (sender == self.repairTypeBtn)//维修分类
    {
        contentCon.list = self.repairTypeArr;
    }
    else if (sender == self.oilBtn)//油量
    {
        contentCon.list = self.oilNamesArr;
    }else if (sender == self.discountModeBtn){//优惠模式
        contentCon.list = self.discountNameArr;
    }else if (sender == self.labourPriceBtn){//工时单价
        contentCon.list = self.labourPrices;
    }
    [contentCon.myTableView reloadData];
}


/** 弹出的回调方法 */
-(void)selectDelegate:(NSInteger)row btn:(UIButton *)btn
{
    NSString *key = nil;
    if (btn == self.serviceAdviserBtn)//服务顾问
    {
        key = self.serviceAdviserArr[row];
    }
    else if (btn == self.jobSheetTypeBtn)//工单类型
    {
        key = self.jobsheetTypeArr[row];
    }
    else if (btn == self.repairTypeBtn)//维修分类
    {
       key = self.repairTypeArr[row];
    }
    else if (btn == self.oilBtn)//油量
    {
        key = self.oilNamesArr[row];
    }else if (btn == self.discountModeBtn){//优惠模式
        key = self.discountNameArr[row];
        MainMenuDataModel *mainModel = [MainMenuDataModel sharedMainMenuDataModel];
        DiscountItem *discount = self.discountModeDic[key];
        self.selectedDiscount = discount;
        //将折扣填入维修项目、零件、附加项目列表中
        [self setDiscountForList:mainModel.repairProjects discount:discount.repairDiscount];
        [self setDiscountForList:mainModel.partList discount:discount.partDiscount];
        [self setDiscountForList:mainModel.attachProjects discount:discount.attachDiscount];
        
        //刷新列表数据
        [self.subView1 setNeedsDisplay];
        [self.subView2 setNeedsDisplay];
        [self.subView3 setNeedsDisplay];
        
        //重新计算金额
        [self computeTheValForJobSheet];
    }else if (btn == self.labourPriceBtn)//油量
    {
        key = self.labourPrices[row];
    }else if (btn == self.sexBtn)//性别
    {
        key = self.sexArr[row];
    }
    
    [btn setTitle:key forState:UIControlStateNormal];
    [self.popCon dismissPopoverAnimated:YES];
    self.popCon = nil;
}

-(void)setDiscountForList:(NSMutableArray *)list discount:(double)discount{
    if (discount == 0) {
        discount = 1;
    }
    for (NSMutableDictionary *data in list) {
        [data setObject:[NSString stringWithFormat:@"%.2f",discount] forKey:@"DISCOUNT"];
    }
}


-(void)getBillDocumentList:(NSNotification*)notification
{
    //（1）获取数据，组织数据
    NSDictionary *theJson = [NSJSONSerialization JSONObjectWithData:(NSData*)notification.object options:NSJSONReadingMutableLeaves error:Nil];
    
//    NSLog(@"%@",theJson);
    _arrOriginalDataForDocumentBill = [theJson objectForKey:@"billDocumentList"];
    _arrDisDataForDocumentBill=[[NSMutableArray alloc] init];
    
    for (int i=0; i<[_arrOriginalDataForDocumentBill count]; i++) {
        
        [_arrDisDataForDocumentBill addObject: [[_arrOriginalDataForDocumentBill objectAtIndex:i] objectForKey:@"billDocument"]];
    }
    
    _arrForThePopViewOriginalData = _arrOriginalDataForDocumentBill;
    _arrForPopTableViewDis = _arrDisDataForDocumentBill;
    
//    NSLog(@"%@",_arrOriginalDataForDocumentBill);
//    NSLog(@"%@",_arrDisDataForDocumentBill);
    
    //（2）刷新下拉菜单的数据
    contentCon.list = _arrForPopTableViewDis;
    [contentCon.myTableView reloadData];
    
    //如果没有获取到数据的话，那么就重新获取数据
    if (nil == _arrForThePopViewOriginalData)
    {
        MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
        NSArray *arrTmp = [NSArray arrayWithObjects:@"vin",[modelIns.dicJobSheetMsg objectForKey:@"vin"], nil];
        [HelpClass getWebServiceDataByString:MM_GET_BILL_DOCUMENT_LIST_ andArrObject:[NSMutableArray arrayWithArray:arrTmp]];
    }
}

-(void)getMileMaxInCarThrough:(NSNotification *)notification
{
    NSDictionary *theJson = [NSJSONSerialization JSONObjectWithData:(NSData*)notification.object options:NSJSONReadingMutableLeaves error:Nil];
    _strMileMaxInCarThrough = [theJson objectForKey:@"maxMileInCarThrough"];
    
    if ([_strMileMaxInCarThrough length] == 0)
    {
        _strMileMaxInCarThrough = @"0";
    }
}

#pragma mark - NIDropDown Delegate method

/*
 NIDropDown 代理方法中的操作是：
 （1）将 dropDown = nil;
 （2）将当前的button title值赋给 业务模型
 */

- (void) niDropDownDelegateMethod: (NIDropDown *) sender
{
    dropDown = nil;
    
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    NSString *str = ((UIButton *)[_arrAllPlaceViewControls objectAtIndex:sender.tag-100]).titleLabel.text;
    
    //将当前的button title值赋给 业务模型
    switch (sender.tag-100)
    {
        case 4:
            [modelIns.dicJobSheetMsg setObject:str forKey:@"evaluatorName"];
            break;
        case 5:
            [modelIns.dicJobSheetMsg setObject:str forKey:@"serviceTypeName"];
            break;
        case 6:
            [modelIns.dicJobSheetMsg setObject:str forKey:@"repairTypeName"];
            break;
        case 8:
            [modelIns.dicJobSheetMsg setObject:str forKey:@"billDocument"];
            break;
        case 9:
            [modelIns.dicJobSheetMsg setObject:str forKey:@"invoiceType"];
            break;
            
        default:
            break;
    }
    
//    NSLog(@"%@",[modelIns.dicJobSheetMsg objectForKey:@"evaluatorName"]);
}

//作业单状态 关联选择算法
/*
 作业单状态选择有两条规则：
 （1）保修 复选框不能人工选择，只能是登录了服务类型为保修或者零部件保修的作业指示，系统才会自动选择 保修 状态
 （2）快修、保修和多客户结算三个复选框不能同时多选，只能选择其中的一项
 */

/*
 本算法的应用：
 当用户点击作业单类型的状态按钮时，调用此方法加以判断，此次操作是否合乎规则
 本算法中的操作是：
 （1）判断快修、保修和多客户结算按钮是否已经存在至少一个，如果是，则此次操作不成功，即状态按钮 不被勾选
 （2）整理数据赋给业务模型类
 */

-(void)jobSheetTypeSelected:(UIButton *)sender
{
//    NSLog(@"%i",sender.tag);
    
    switch (sender.tag)
    {
        //多客户结算
        case 115:
            [self setUpTheJobSheetTypeBtnBasedOnTag:115 andType:duokehujiesuan = !duokehujiesuan];
            if (duokehujiesuan == YES)
            {
                [((UIButton *)[self.view viewWithTag:multipleCustomerAllocationJumpBtnTag]) setHidden:NO];
            }
            else
            {
                [((UIButton *)[self.view viewWithTag:multipleCustomerAllocationJumpBtnTag]) setHidden:YES];
            }
            break;
            
        default:
            break;
    }
    
    //更新业务模型中的数据
    NSString *strJobSheetTypeTmp = @"";
    if (YES == duokehujiesuan)
    {
        strJobSheetTypeTmp = [strJobSheetTypeTmp stringByAppendingString:@"多客户结算"];
    }
    
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    [modelIns.dicJobSheetMsg setObject:strJobSheetTypeTmp forKey:@"jobSheetType"];
    
//    NSLog(@"%@",[modelIns.dicJobSheetMsg objectForKey:@"jobSheetType"]);
}

//创建多客户选择 跳转 按钮
-(void)createMultipleCustomerAllocationJumpBtn
{
    if (YES == duokehujiesuan)
    {
        //创建一个按钮
    }
}

//初始化作业单状态 按钮
/*
 保修、返修、二手车翻新、快修、多客户结算 tag---[111,115]
 */

-(void)initTheJobSheetTypeBtn
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    NSString *strType = [modelIns.dicJobSheetMsg objectForKey:@"jobSheetType"];
    
    
    NSRange range = [strType rangeOfString:@"多客户结算"];
    if (range.length == [@"多客户结算" length])
    {
        [self setUpTheJobSheetTypeBtnBasedOnTag:115 andType:YES];
        duokehujiesuan = YES;
    }
    else
    {
        [self setUpTheJobSheetTypeBtnBasedOnTag:115 andType:NO];
        duokehujiesuan = NO;
        [((UIButton *)[self.view viewWithTag:multipleCustomerAllocationJumpBtnTag]) setHidden:YES];
    }
    
    
    for (int i = 112; i<=115; i++)
    {
        [((UIButton *)[self.view viewWithTag:i]) addTarget:self action:@selector(jobSheetTypeSelected:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    [((UIButton *)[self.view viewWithTag:500]) addTarget:self action:@selector(jobSheetTypeSelected:) forControlEvents:UIControlEventTouchUpInside];
}

//设置按钮的状态
-(void)setUpTheJobSheetTypeBtnBasedOnTag:(NSInteger)tag andType:(bool)type
{
    //YES 表示被选中，否则 未选中
    if (YES == type)
    {
        [(UIButton *)[self.view viewWithTag:tag] setBackgroundImage:[UIImage imageNamed:@"mm_red_btn.png"] forState:UIControlStateNormal];
        [((UIButton *)[self.view viewWithTag:tag]) setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }
    else
    {
        [(UIButton *)[self.view viewWithTag:tag] setBackgroundImage:[UIImage imageNamed:@"mm_gray_btn.png"] forState:UIControlStateNormal];
        [((UIButton *)[self.view viewWithTag:tag]) setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    }
}


//-(void)dismissModalViewControllerAnimated:(BOOL)animated
//{
//    [super dismissModalViewControllerAnimated:animated];
//    
//    [_vcPopViewForSendMessage saveTelNumber];
//}

-(void)setUpTheStateBtnByBtn:(UIButton *)btn andState:(BOOL)state
{
    if (STATE_BUTTON_ON_ == state)
    {
        [btn setBackgroundImage:[UIImage imageNamed:@"mm_red_btn.png"] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }
    else
    {
        [btn setBackgroundImage:[UIImage imageNamed:@"mm_gray_btn.png"] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    }
}

#pragma mark - 保存相关方法

- (IBAction)saveBtnPressed:(UIButton *)sender
{
    
    NSString *errMsg = [self validInput];
    if (errMsg) {
        [SVProgressHUD dismiss];
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:errMsg delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alerVeiw show];
        return;
    }

    [SVProgressHUD showWithStatus:@"正在保存请等待...."];
    //保存数据
    [self saveAllDataToMainMenuModel];
    
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:modelIns.dicJobSheetMsg options:NSJSONWritingPrettyPrinted error:NULL];
    
    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

    NSDictionary *param = @{@"JSON_STRING":jsonStr};
    
    NSMutableArray *imageDataArr = [self getImageDataArr];//获取图片二进制数据
    [MyAFNetWorkManager postWithParam:imageDataArr mainImage:nil parameters:param andActionString:@"MAINTAIN_REPAIR_ORDER_FOR_PAD" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
      
        int success = [obj[@"SUCCESS"]integerValue];
        modelIns.nRowForRepairItemList = -1;
        modelIns.nRowForPartList = -1;
        modelIns.nRowForOtherChargeList = -1;
        if (error||success<1) {
              [SVProgressHUD dismiss];
            UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"保存失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alerVeiw show];
            return;
        }else{
            
          
            //重新刷新数据
            NSString *roNo = nil;
            if (self.optType == operationTypeAdd) {
                roNo = obj[@"RO_NO"];
            }else{
                roNo = self.roNoLbl.text;
            }
            //保存环检单pad
            [self saveCheckOrder:roNo];
        }
    }];

}
-(void)saveCheckOrder:(NSString*)ro_no{
//    NSDictionary *dic = @{@"RO_NO":roNo,@"VIN":self.vinLbl.text};
    //保存环检单
    NSMutableArray *imageDataArr =[NSMutableArray array];
    //添加环车图
    NSData *imgData = UIImageJPEGRepresentation([self writeHuanCarImg], 1.0);
    [imageDataArr addObject:imgData];
    NSString*CHECK_PIC_NAME=@"File0.jpg";
    //用户签名图
    NSString*CUSTOMER_SIGN_NAM=@"";
    if (self.customerWriteView.image) {
        //签名图
        NSData *imgData = UIImageJPEGRepresentation(self.customerWriteView.image, 1.0);
        [imageDataArr addObject:imgData];
        CUSTOMER_SIGN_NAM=@"File1.jpg";
    }
    [imageDataArr addObjectsFromArray:[self getImageDataArr]];
//    NSString *remark = self.remarksText.text;
    //拼接编号
    MainMenuDataModel *mainModel = [MainMenuDataModel sharedMainMenuDataModel];
    
    NSMutableArray*DEC_NO=[NSMutableArray array];
    NSMutableArray*DEC_TYPE=[NSMutableArray array];
    NSMutableArray*DEC_NUMBER=[NSMutableArray array];
    NSMutableArray*REMARK=[NSMutableArray array];
    NSMutableArray*ITEM_ID=[NSMutableArray array];
    ;
    for (NSDictionary*checkDit in mainModel.arrOutCheck) {
       
        [DEC_NO addObject:checkDit[MM_OUT_CHECK_OUT_CHECK_NUMBER_KEY_STR_]];
        [DEC_TYPE addObject:checkDit[MM_OUT_CHECK_CHECK_ITEM_KEY_STR_]];
        [DEC_NUMBER addObject:checkDit[MM_OUT_CHECK_DEFECT_COUNT_KEY_STR_]];
        [REMARK addObject:checkDit[MM_OUT_CHECK_DEFECT_DESCRIPTION_KEY_STR_]];
        [ITEM_ID addObject:checkDit[@"ITEM_ID"]];
    }
    //修改工单必须传这个
    NSString*PC_NO=@"";
    if(self.repairOrderInfoModel){
        HJRepairOrderInfoCheckOrderModel*repairOrderInfoCheckOrderModel=self.repairOrderInfoModel.TT_RO_CHECK_ORDER[0];
        PC_NO=repairOrderInfoCheckOrderModel.PC_NO;
    }
    
    if (!PC_NO) {
        PC_NO=@"";
    }
    if (!ro_no) {
        ALERT(@"缺少ro_no");
        return;
    }
    
    NSDictionary *dic=@{
                        @"SPCICAL_DEC":specialTipsTextView.text.length?specialTipsTextView.text:@"",//特别说明
                        @"PC_NO":PC_NO,
                        @"IS_WINDOW":self.IS_WINDOW.length?self.IS_WINDOW:@"",
                        @"IS_CHAIR":self.IS_CHAIR.length?self.IS_CHAIR:@"",
                        @"IS_SOUND":self.IS_SOUND.length?self.IS_SOUND:@"",
                        @"IS_AIR":self.IS_AIR.length?self.IS_AIR:@"",
                        @"IS_GLASS":self.IS_GLASS.length?self.IS_GLASS:@"",
                        @"IS_SMOKE":self.IS_SMOKE.length?self.IS_SMOKE:@"",
                        @"IS_SAFE":self.IS_SAFE.length?self.IS_SAFE:@"",
                        @"HAS_LIFT":self.HAS_LIFT.length?self.HAS_LIFT:@"",
                        @"HAS_TOOL":self.HAS_TOOL.length?self.HAS_TOOL:@"",
                        @"HAS_BACK":self.HAS_BACK.length?self.HAS_BACK:@"",
                        @"HAS_GLASS":self.HAS_GLASS.length?self.HAS_GLASS:@"",
                        
                        @"RO_NO":ro_no,
                        @"ITEM_ID":[ITEM_ID mj_JSONString],
                        @"DEC_NO":[DEC_NO mj_JSONString],
                        @"DEC_TYPE":[DEC_TYPE mj_JSONString],
                        @"DEC_NUMBER":[DEC_NUMBER mj_JSONString],
                        @"REMARK":[REMARK mj_JSONString],
                        @"CHECK_PIC_NAME":CHECK_PIC_NAME,
                        @"CUSTOMER_SIGN_NAME":CUSTOMER_SIGN_NAM,
                        @"SPCICAL_DEC":self.SPCICAL_DEC.length?self.SPCICAL_DEC:@"",
                        @"HAS_EXTINGUISH":self.HAS_EXTINGUISH.length?self.HAS_EXTINGUISH:@"",
                        @"HAS_WARN":self.HAS_WARN.length?self.HAS_WARN:@"",
                       
                        };
    [MyAFNetWorkManager postWithParam:imageDataArr mainImage:nil parameters:dic andActionString:@"TT_RO_CHECK_ORDER_FOR_PAD" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
        [SVProgressHUD dismiss];
        int success = [obj[@"SUCCESS"]integerValue];
        if (error||success<1) {
            UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"保存失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alerVeiw show];
            return;
        }else{
            UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"保存成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alerVeiw show];
            if (self.returnBack) {
                self.returnBack();
            }
            [self.navigationController popViewControllerAnimated:YES];
//            //重新刷新数据
//             [self getJobsheetDetailWithRoNo:ro_no];
        }
    }];
}
-(UIImage*)writeHuanCarImg{
    //截取环车图
    CGSize s = self.picRemarkBtn.bounds.size;
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了
    UIGraphicsBeginImageContextWithOptions(s, NO, [UIScreen mainScreen].scale);
    [self.picRemarkBtn.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
/** 基本信息非空验证 */
-(NSString *)validInput{
    NSString *msg = nil;
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    mm_picRecodeDataModel *picDataModel = [mm_picRecodeDataModel sharedModelIns];

    if (self.serviceAdviserBtn.titleLabel.text.length<=0) {
        msg = @"请选择服务顾问";
    }else if (self.jobSheetTypeBtn.titleLabel.text.length<=0){
        msg = @"请选择工单类型";
    }else if (self.repairTypeBtn.titleLabel.text.length<=0){
        msg = @"请选择维修分类";
    }else if (self.labourPriceBtn.titleLabel.text.length<=0){
        msg = @"请选择工时单价";
    }else if (self.contactName.text.length<=0){
        msg = @"请输入送修人姓名";
    }else if (self.carOwnerNameTxt.text.length<=0){
        msg = @"请输入车主姓名";
    }else if (!self.contactPhone.text.length||self.contactPhone.text.length!=11){
        msg = @"请正确填写送个人手机号码";
    }else if (self.mileageTxt.text.length<=0){
        msg = @"请输入里程数";
    }else if ([self.mileageTxt.text doubleValue]<self.lastMileage){
        msg = @"里程数不能小于最后一次进厂里程";
    }else if (self.sumitCarDateBtn.titleLabel.text.length<=0){
        msg = @"请选择预定交车时间";
    }else if (!self.sexBtn.titleLabel.text.length){
        msg = @"请选择送修人性别";
    }else if (!modelIns.repairProjects.count){
        msg=@"维修项目为必填项,至少有一个维修项目";
    }else if(self.customerWriteView.image == nil){
        msg=@"请完成客户签署！";

    }
    else{
        NSDate *curDate = [NSDate date];
        NSDate *prepDate = [self.dateFormatter dateFromString:self.sumitCarDateBtn.titleLabel.text];
        NSComparisonResult comparisonResult = [curDate compare:prepDate];
        if (comparisonResult == NSOrderedDescending) {
            return @"预定交车时间不能小于当前时间";
        }
        msg = [self validRepairProjects];
        if (msg) {
            return msg;
        }
        msg = [self validPartList];
        if (msg) {
            return msg;
        }
    }
    
    return msg;
}

/** 维修项目非空验证 */
-(NSString *)validRepairProjects{
    NSString *msg = nil;
    MainMenuDataModel *mainModel = [MainMenuDataModel sharedMainMenuDataModel];
    if (mainModel.repairProjects.count>0) {
        for (NSDictionary *dic in mainModel.repairProjects) {
            id price = dic[@"LABOUR_PRICE"];
            if (!price) {
                msg = @"维修项目列表存在缺失工时单价列！";
                return msg;
            }
        }
    }
    return msg;
}

/** 零件列表非空验证 */
-(NSString *)validPartList{
    NSString *msg = nil;
    MainMenuDataModel *mainModel = [MainMenuDataModel sharedMainMenuDataModel];
    if (mainModel.partList.count>0) {
        for (NSDictionary *dic in mainModel.partList) {
            id price = dic[@"PART_SALES_PRICE"];
            if (!price) {
                msg = @"零件列表存在缺失销售单价列！";
                return msg;
            }
        }
    }
    return msg;
}

-(void)getJobsheetDetailWithRoNo:(NSString *)roNo{
    [SVProgressHUD showSuccessWithStatus:@"保存成功，正在刷新界面...."];
    NSDictionary *dic = @{@"RO_NO":roNo,@"VIN":self.vinLbl.text};
    //查询工单
    [MyAFNetWorkManager postWithParam:dic andAction:@"QUERY_REPAIR_ORDER_DETAIL_PAD" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
        
        MainMenuDataModel *mainModel = [MainMenuDataModel sharedMainMenuDataModel];
        mainModel.deletedRepairProjects = nil;
        mainModel.deletedPartList = nil;
        mainModel.deletedAttachProjects = nil;
        mainModel.arrOutCheckDeleted = nil;
        mm_picRecodeDataModel *picDataModel = [mm_picRecodeDataModel sharedModelIns];
        picDataModel.arrForNewImage = nil;
        if (error) {
            [SVProgressHUD dismiss];
            UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"刷新数据失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alerVeiw show];
            return;
        }else{
            NSMutableArray *arr = obj[@"TM_VEHICLE"];//预交款
            NSDictionary *predic = arr[0];
            NSMutableDictionary *baseInfo = obj[@"TT_REPAIR_ORDER"][0];
            [baseInfo setObject:predic[@"PRE_PAY"] forKey:@"PRE_PAY"];
            id curMileage = predic[@"CURRENT_MILEAGE"];
            [baseInfo setObject:curMileage?curMileage:@"0" forKey:@"CURRENT_MILEAGE"];
            mainModel.dicBaseMessage = baseInfo;//基本信息
            mainModel.arrOutCheck = obj[@"TT_DEFECT"];//缺陷
            mainModel.repairProjects = obj[@"TT_RO_LABOUR"];//维修项目
            mainModel.partList = obj[@"TT_RO_REPAIR_PART"];//零件
            mainModel.attachProjects = obj[@"TT_RO_ADD_ITEM"];//附加项目
            mainModel.arrCarryGoods = obj[@"TT_RO_CONFIRM"];//物品确认
            mainModel.arrImageList = obj[@"TT_RO_FILE"];//图片列表
            self.optType = operationTypeModify;
            [self setUpValForAllPlaceViewControls];
            [self updateDataSubView1];
            [self updateDataSubView2];
            [self updateDataSubView3];
            [SVProgressHUD dismiss];
        }
    }]; 
}
-(void)saveAllDataToMainMenuModel
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
     NSDictionary *baseInfoDic = modelIns.dicBaseMessage;
    modelIns.dicJobSheetMsg = [NSMutableDictionary dictionary];
    
    //基本信息保存
    NSString *roNo = self.optType == operationTypeAdd ? @"" : self.roNoLbl.text.length?self.roNoLbl.text:@"";
    [modelIns.dicJobSheetMsg setObject:roNo forKey:@"RO_NO"];//工单号
    NSString*SERVICE_ADVISOR=self.serviceAdviserDic[self.serviceAdviserBtn.titleLabel.text];
    [modelIns.dicJobSheetMsg setObject:SERVICE_ADVISOR.length?SERVICE_ADVISOR:@"" forKey:@"SERVICE_ADVISOR"];//服务顾问
    [modelIns.dicJobSheetMsg setObject:self.ownerNo.length?self.ownerNo:@"" forKey:@"OWNER_NO"];//车主编号
    NSString*OWNER_PROPERTY=[NSString stringWithFormat:@"%zd",[baseInfoDic[@"OWNER_PROPERTY"] integerValue]];
     [modelIns.dicJobSheetMsg setObject:OWNER_PROPERTY.length?OWNER_PROPERTY:@"" forKey:@"OWNER_PROPERTY"];//车主信息
    [modelIns.dicJobSheetMsg setObject:self.carOwnerNameTxt.text.length?self.carOwnerNameTxt.text:@"" forKey:@"OWNER_NAME"];//车主姓名
    [modelIns.dicJobSheetMsg setObject:self.contactName.text.length?self.contactName.text:@"" forKey:@"DELIVERER"];//送修人
    [modelIns.dicJobSheetMsg setObject:self.contactPhone.text.length?self.contactPhone.text:@"" forKey:@"DELIVERER_MOBILE"];//联系人手机
    [modelIns.dicJobSheetMsg setObject:[self.jobsheetTypeDic[self.jobSheetTypeBtn.titleLabel.text] length]?self.jobsheetTypeDic[self.jobSheetTypeBtn.titleLabel.text]:@""  forKey:@"RO_TYPE"];//工单类型
    NSString*REPAIR_TYPE_CODE=self.repairTypeDic[self.repairTypeBtn.titleLabel.text];
    [modelIns.dicJobSheetMsg setObject:REPAIR_TYPE_CODE.length?REPAIR_TYPE_CODE:@"" forKey:@"REPAIR_TYPE_CODE"];//维修分类
    NSString*DELIVERER_GENDER=self.sexDic[self.sexBtn.titleLabel.text];
    [modelIns.dicJobSheetMsg setObject:DELIVERER_GENDER.length?DELIVERER_GENDER:@"" forKey:@"DELIVERER_GENDER"];//性别
    
    //
    [modelIns.dicJobSheetMsg setObject:self.yuyueOrderLabel.text.length?self.yuyueOrderLabel.text:@"" forKey:@"BOOKING_ORDER_NO"];//预约单号
    
    modelIns.dicJobSheetMsg[@"LABOUR_PRICE"] = self.labourPriceBtn.titleLabel.text;//工时单价
    [modelIns.dicJobSheetMsg setObject:self.licenseLbl.text.length?self.licenseLbl.text:@"" forKey:@"LICENSE"];//车牌号
    [modelIns.dicJobSheetMsg setObject:self.vinLbl.text.length?self.vinLbl.text:@"" forKey:@"VIN"];//车架号
    //保存车型
    NSString*MODEL=baseInfoDic[@"MODEL"];
    [modelIns.dicJobSheetMsg setObject:MODEL?MODEL:@"" forKey:@"MODEL"];
//    //保存yu
//     [modelIns.dicJobSheetMsg setObject:baseInfoDic[@"MODEL"] forKey:@"MODEL"];
//    [modelIns.dicJobSheetMsg setObject:self.createDateLbl.text forKey:@"CREATE_DATE"];//接待日期
    [modelIns.dicJobSheetMsg setObject:self.mileageTxt.text.length?self.mileageTxt.text:@"" forKey:@"IN_MILEAGE"];//里程数
    [modelIns.dicJobSheetMsg setObject:self.orderRemark.text.length?self.orderRemark.text:@"" forKey:@"REMARK"];//备注
    NSString *oil = nil;
    if (self.oilBtn.titleLabel.text.length>0) {
        oil = self.oilDic[self.oilBtn.titleLabel.text];
    }else{
        oil = @"";
    }
    [modelIns.dicJobSheetMsg setObject:oil forKey:@"OIL_REMAIN"];//油量
    [modelIns.dicJobSheetMsg setObject:specialTipsTextView.text.length?specialTipsTextView.text:@"" forKey:@"ITEMS_SPECIAL_DESC"];//特别说明

     //功能确认信息保存
    NSString*TROUBLE_CONFIRM=[self getValuesFromSelectedBtnsWithDicArr:self.funtionDicBtns];
    [modelIns.dicJobSheetMsg setObject:TROUBLE_CONFIRM.length?TROUBLE_CONFIRM:@"" forKey:@"TROUBLE_CONFIRM"];
    
    //物品确认信息保存
    [self saveCarryGoodsData];
    
    //图片
    [self saveImgList];
    
    //录音
//    [self saveRecordList];
    //外观检查信息保存
    [self saveDefectList];
    
    //维修项目、零件、附加项目信息保存
    [self saveResultsData];
    
    //费用细节信息保存
    [self saveChargeDetailData];
    
    //页面最下边的状态按纽状态保存
    [self saveTheLastStateBtnData];
    
    //如果服务活动不参加原因有数据  关联modelIns.activeReasonArr 到modelIns.dicJobSheetMsg
    if (modelIns.activeReasonArr.count>0) {
    [modelIns.dicJobSheetMsg setValue:modelIns.activeReasonArr forKey:@"TT_ACTIVITY_REFUSE_REASON"];
    }
}

//保存被删除的图片
-(void)saveImgList
{
    mm_picRecodeDataModel *picDataModel = [mm_picRecodeDataModel sharedModelIns];
    if (picDataModel.arrForDeletedImages) {
        MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
        [modelIns.dicJobSheetMsg setObject:picDataModel.arrForDeletedImages forKey:@"TT_RO_FILE"];
    }
    
}

-(NSMutableArray *)getImageDataArr{
//    UIImage *image = [UIImage imageNamed:@"短信按钮"];
//    NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
//    NSMutableArray *imageArr = [NSMutableArray array];
//    [imageArr addObject:imgData];
    mm_picRecodeDataModel *picDataModel = [mm_picRecodeDataModel sharedModelIns];
    if (picDataModel.arrForNewImage.count>0) {
        NSMutableArray*arr=[NSMutableArray array];
        for (PhotoModel *pm in picDataModel.arrForNewImage) {

           NSData *imgData = UIImageJPEGRepresentation(pm.image, 1.0);
            [arr addObject:imgData];
        }
        return arr;
    }
    return nil;
}

//录音列表保存
-(void)saveRecordList
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    modelIns.dicJobSheetMsg = [NSMutableDictionary dictionaryWithDictionary:modelIns.dicJobSheetMsg];
    [modelIns.dicJobSheetMsg setObject:modelIns.arrRecodeList forKey:@"recordList"];
}


//物品确认信息保存
-(void)saveCarryGoodsData
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    for (int i = 0; i< modelIns.arrCarryGoods.count; i++) {
        NSMutableDictionary *dic = modelIns.arrCarryGoods[i];
        NSString *name = dic[@"ITEMS_NAME"];
        if (!dic[@"STATUS"]) {
            [dic setObject:@"U" forKey:@"STATUS"];
        }
        if ([name isEqualToString:@"香烟"]||[name isEqualToString:@"酒"]||[name isEqualToString:@"现金"]) {
            [dic setObject:self.cigaretteRemarkTxt.text forKey:@"REMARK"];
        }
    }//end for
    
    if (modelIns.arrCarryGoods) {
        //将最终结果保存在业务模型中的大字典中
        [modelIns.dicJobSheetMsg setObject:modelIns.arrCarryGoods forKey:@"TT_RO_CONFIRM"];
    }    
}

/** 保存缺陷列表 */
-(void)saveDefectList{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    if (modelIns.arrOutCheck.count||modelIns.arrOutCheckDeleted.count) {
        [self setStatusForDicArr:modelIns.arrOutCheck];
        if (modelIns.arrOutCheckDeleted.count) {
            NSRange range = {0,modelIns.arrOutCheckDeleted.count};
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
            [modelIns.arrOutCheck insertObjects:modelIns.arrOutCheckDeleted atIndexes:indexSet];
        }
        [modelIns.dicJobSheetMsg setObject:modelIns.arrOutCheck forKey:@"TT_DEFECT"];
    }
}


/** 维修项目、零件、附加项目信息保存 */
-(void)saveResultsData
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    if (modelIns.repairProjects.count||modelIns.deletedRepairProjects.count) {
        [self setStatusForDicArr:modelIns.repairProjects];
        if (modelIns.deletedRepairProjects.count) {
            NSRange range = {0,modelIns.deletedRepairProjects.count};
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
            [modelIns.repairProjects insertObjects:modelIns.deletedRepairProjects atIndexes:indexSet];
        }
        [modelIns.dicJobSheetMsg setObject:modelIns.repairProjects forKey:@"TT_RO_LABOUR"];
    }
    
    if (modelIns.partList.count||modelIns.deletedPartList.count) {
        [self setStatusForDicArr:modelIns.partList];
        if (modelIns.deletedPartList.count) {
            NSRange range = {0,modelIns.deletedPartList.count};
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
            [modelIns.partList insertObjects:modelIns.deletedPartList atIndexes:indexSet];
        }
        [modelIns.dicJobSheetMsg setObject:modelIns.partList forKey:@"TT_RO_REPAIR_PART"];
    }
    
    if (modelIns.attachProjects.count||modelIns.deletedAttachProjects.count) {
        [self setStatusForDicArr:modelIns.attachProjects];
        if (modelIns.deletedAttachProjects.count) {
            NSRange range = {0,modelIns.deletedAttachProjects.count};
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
            [modelIns.attachProjects insertObjects:modelIns.deletedAttachProjects atIndexes:indexSet];
        }
        [modelIns.dicJobSheetMsg setObject:modelIns.attachProjects forKey:@"TT_RO_ADD_ITEM"];
    }
}

-(void)setStatusForDicArr:(NSArray *)dataList{
    for (NSMutableDictionary *dic in dataList) {
        if (!dic[@"STATUS"]) {
            [dic setObject:@"U" forKey:@"STATUS"];
        }
    }
}

//费用细节信息保存
-(void)saveChargeDetailData
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    
    [modelIns.dicJobSheetMsg setObject:self.attachChargeTxt.text.length?self.attachChargeTxt.text:@"" forKey:@"ADD_ITEM_AMOUNT"];//附加项目费
    [modelIns.dicJobSheetMsg setObject:self.attachChargeTxt.text.length?self.attachChargeTxt.text:@"" forKey:@"REAL_ADD_ITEM_AMOUNT"];//应付附加项目费
    
    
    
    [modelIns.dicJobSheetMsg setObject:self.workHourDiscountTxt.text.length?self.workHourDiscountTxt.text:@"" forKey:@"LABOUR_DISCOUNT"];//工费折扣
    
    [modelIns.dicJobSheetMsg setObject:self.partDiscountTxt.text.length?self.partDiscountTxt.text:@"" forKey:@"PART_DISCOUNT"];//零件折扣
    
    [modelIns.dicJobSheetMsg setObject:self.sumitCarDateBtn.titleLabel.text forKey:@"END_TIME_SUPPOSED"];//预定交车日期
    
    [modelIns.dicJobSheetMsg setObject:self.workHourChargeTxt.text.length?self.workHourChargeTxt.text:@"" forKey:@"LABOUR_AMOUNT"];//工时费
    
     [modelIns.dicJobSheetMsg setObject:self.workHourChargeTxt.text.length?self.workHourChargeTxt.text:@"" forKey:@"REAL_LABOUR_AMOUNT"];//实时工时费
    
    [modelIns.dicJobSheetMsg setObject:self.firstRepairChargeTxt.text.length?self.firstRepairChargeTxt.text:@"" forKey:@"IS_FIRST_MAINTAIN"];//首保费用
    
    //    [modelIns.dicJobSheetMsg setObject:@"123" forKey:@"ESTIMATE_AMOUNT"];//预算费用
    
    [modelIns.dicJobSheetMsg setObject:self.partChargeTxt.text.length?self.partChargeTxt.text:@"" forKey:@"REPAIR_PART_AMOUNT"];//零件费
     [modelIns.dicJobSheetMsg setObject:self.partChargeTxt.text.length?self.partChargeTxt.text:@"" forKey:@"REAL_REPAIR_PART_AMOUNT"];//应零件费
    
    [modelIns.dicJobSheetMsg setObject:self.totalAmountTxt.text.length?self.totalAmountTxt.text:@"" forKey:@"REPAIR_AMOUNT"];//应负总金额
    
    
    
//    [modelIns.dicJobSheetMsg setObject:self.beforPayTxt.text.length?self.beforPayTxt.text:@"" forKey:@"PRE_PAY"];//预交款
    
    //    [modelIns.dicJobSheetMsg setObject:@"123" forKey:@"ARREARAGE_AMOUNT"];//欠款金额
    NSString *discountCode = self.selectedDiscount ? self.selectedDiscount.code :@"";
    [modelIns.dicJobSheetMsg setObject:discountCode forKey:@"DISCOUNT_MODE_CODE"];//优惠模式
}

//页面最下边的状态按纽状态保存
-(void)saveTheLastStateBtnData
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    NSString *valY = @"12781001";
    NSString *valN = @"12781002";
    [modelIns.dicJobSheetMsg setObject:self.washCarBtn.selected?valY:valN forKey:@"IS_WASH"];
    
    [modelIns.dicJobSheetMsg setObject:self.waitBtn.selected?valY:valN forKey:@"IS_CUSTOMER_IN_ASC"];

    [modelIns.dicJobSheetMsg setObject:self.takeOldPartBtn.selected?valY:valN forKey:@"IS_TAKE_PART_OLD"];
}

//派工和打印按钮
-(void)createPaiGongAndDaYinBtn
{
    UIButton *paiGongBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    paiGongBtn.frame = CGRectMake(400, 1500, 73, 44);
    [paiGongBtn setBackgroundColor:[UIColor lightGrayColor]];
    [paiGongBtn setTitle:@"派工" forState:UIControlStateNormal];
    paiGongBtn.tag = paiGongBtnTag;
    [paiGongBtn addTarget:self action:@selector(paiGongAndDaYinBtnSelected:) forControlEvents:UIControlEventTouchUpInside];
    [self setUpTheStateBtnByBtn:paiGongBtn andState:STATE_BUTTON_ON_];
    [self.scrollView addSubview:paiGongBtn];
    
    UIButton *daYinBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    daYinBtn.frame = CGRectMake(493,1500,73,44);
    [daYinBtn setBackgroundColor:[UIColor lightGrayColor]];
    [daYinBtn setTitle:@"打印" forState:UIControlStateNormal];
    daYinBtn.tag = daYinBtnTag;
    [daYinBtn addTarget:self action:@selector(paiGongAndDaYinBtnSelected:) forControlEvents:UIControlEventTouchUpInside];
    [self setUpTheStateBtnByBtn:daYinBtn andState:STATE_BUTTON_ON_];
    [self.scrollView addSubview:daYinBtn];
    
    [self hiddenThePaiGongAndDaYinBtn];
}

-(void)hiddenThePaiGongAndDaYinBtn
{
    [((UIButton *)[self.view viewWithTag:paiGongBtnTag]) setHidden:YES];
    [((UIButton *)[self.view viewWithTag:daYinBtnTag]) setHidden:YES];
}

-(void)displayThePaiGongAndDaYinBtn
{
    [((UIButton *)[self.view viewWithTag:paiGongBtnTag]) setHidden:NO];
    [((UIButton *)[self.view viewWithTag:daYinBtnTag]) setHidden:NO];
}

/*
 派工和打印按钮的回调方法操作：
 （1）根据tag值区分按钮，然后用分支语句分别处理按钮点击动作，派工 和 打印 指示进行界面跳转，待添加。。。
 */

-(void)paiGongAndDaYinBtnSelected:(UIButton *)sender
{
//    NSLog(@"paiGongAndDaYinBtnSelected !!!");
    
    if (sender.tag == paiGongBtnTag)
    {
        //派工按钮按下
    }
    else
    {
        //打印按钮按下
    }
}

#pragma mark - 给外观检查的图片（btn）上放置标记

-(void)createRemarksOnOutCheckBtn
{
    //remove掉 btn 上所有的子视图：
    NSArray *subViewsIns = [self.picRemarkBtn subviews];
    for (int i = 1; i<[subViewsIns count]; i++)
    {
        [(UIView *)[subViewsIns objectAtIndex:i] removeFromSuperview];
    }
    //进行标记
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    for (int i = 0; i<modelIns.arrOutCheck.count; i++)
    {
        NSString *strPoint = modelIns.arrOutCheck[i][MM_OUT_CHECK_POINT_KEY_STR_];
        NSRange range = [strPoint rangeOfString:@","];
        
        if (NSNotFound == range.location)
        {
            continue;
        }
        CGFloat cgPointX = [[strPoint substringToIndex:range.location] floatValue];
        CGFloat cgPointY = [[strPoint substringFromIndex:range.location+1] floatValue];
        
        NSString *strNumber = [[modelIns.arrOutCheck objectAtIndex:i] objectForKey:MM_OUT_CHECK_OUT_CHECK_NUMBER_KEY_STR_];
        
        //给该坐标上添加一个编号图标
        UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(cgPointX-10, cgPointY-10, 20, 20)];
        lbl.text = strNumber;
        lbl.textColor = [UIColor redColor];
        lbl.font = [UIFont systemFontOfSize:13];
        lbl.backgroundColor = [UIColor clearColor];
        [self.picRemarkBtn addSubview:lbl];
    }
}

#pragma mark - 键盘托起屏幕的代理方法

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    // When the user presses return, take focus away from the text field so that the keyboard is dismissed.
    
    if (107 == textField.tag||110 == textField.tag)
    {
        return NO;
    }
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);
    self.view.frame = rect;
    [UIView commitAnimations];
    [textField resignFirstResponder];
    return YES;
}
- (NSString *)getGongdanzhuangtai:(NSString *)code
{
    NSArray *zidianArr=[self readershuDICimform][@"TM_RO_STATUS"];
    for (NSDictionary *dic in zidianArr) {
        if ([dic[@"CODE"] isEqualToString:code]) {
            
            return dic[@"NAME"];
        }
    }
    return nil;
}
#pragma mark - UITextFieldDelegate代理方法


-(void)textFieldValueChange:(NSNotification *)note{
    if (self.currentEditingTxt == self.contactPhone && self.contactPhone.text.length>11) {
        NSRange range = {0,11};
        self.contactPhone.text = [self.contactPhone.text substringWithRange:range];
    }
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    
    //存储费用列表输入的值
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    modelIns.dicChargeDetail = [NSMutableDictionary dictionaryWithDictionary:modelIns.dicChargeDetail];

    
    //刷新费用列表
    [self computeTheValForJobSheet];
    
    //判断公里数是否正常
    if (self.mileageTxt == textField)
    {
//        if ([self isMileBeyond10000KM])
//        {
//            //弹出提示框，超过10000公里
//            double dTmp = [self.mileageTxt.text doubleValue]-[_strMileMaxInCarThrough doubleValue];
//            UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"你输入的公里数超过最低允许输入值 %lf",dTmp] delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
//            [alerVeiw show];
//        }
//        else
        if ([self isMileBelowMileMax])
        {
            //弹出提示框，里程不低于历史最高里程
            UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"您输入的里程数不能低于 %0.2f KM",[_strMileMaxInCarThrough doubleValue]]delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
            [alerVeiw show];
        }
    }
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.currentEditingTxt = textField;
//    textField.keyboardType = UIKeyboardTypeNumberPad;
//    int offset = 350;//键盘高度350
//    NSTimeInterval animationDuration = 0.30f;
//    [UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
//    [UIView setAnimationDuration:animationDuration];
//    float width = self.view.frame.size.width;
//    float height = self.view.frame.size.height;
//    if(offset > 0)
//    {
//        CGRect rect = CGRectMake(0.0f, -offset,width,height);
//        self.view.frame = rect;
//    }
//    [UIView commitAnimations];
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    return true;
//    if (136 == textField.tag
//        ||
//        137 == textField.tag
//        ||
//        138 == textField.tag)
//    {
//        return YES;
//    }
//    
//    NSCharacterSet *cs;
//    cs = [[NSCharacterSet characterSetWithCharactersInString:@".0123456789\n"]invertedSet];
//    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""];
//    BOOL canChange = [string isEqualToString:filtered];
    
    //只能输入带小数点后两位，判断如果有小数点
//    if ([textField.text rangeOfString:@"."].length == 1
//        &&
//        [textField.text length]-([textField.text rangeOfString:@"."].location+1)>=2
//        )
//    {
//        canChange = NO;
//    }
    
    
}

//注册键盘消息
-(void)registerNotificationForKeyBoard
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setViewNormal) name:UIKeyboardWillHideNotification object:nil];
}

//视图回归正常状态
-(void)setViewNormal
{
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);
    self.view.frame = rect;
    [UIView commitAnimations];
}


-(void)setupDropdownBackgroundWithFrame:(CGRect)frame{
    UIView *bg = [[UIView alloc] initWithFrame:frame];
    bg.backgroundColor = [UIColor lightGrayColor];
    [self.scrollView addSubview:bg];
}

-(UIButton *)setupDrodownBtnWithBgFrame:(CGRect)bgFrame method:(SEL)method{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setBackgroundImage:[UIImage imageNamed:@"10.png"] forState:UIControlStateNormal];
    btn.frame = CGRectMake(bgFrame.origin.x-1, bgFrame.origin.y-3, bgFrame.size.width+2, bgFrame.size.height+6);
    [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:13];
    btn.titleLabel.numberOfLines = 2;
    [btn addTarget:self action:method forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:btn];
    return btn;
}

#pragma mark - 预计完工时间

//创建和预定交车日btn
-(void)createCompleteDateBtn
{
    CGRect bgFrame = CGRectMake(599, 205, 140, 35);
    [self setupDropdownBackgroundWithFrame:bgFrame];
    
    self.sumitCarDateBtn = [self setupDrodownBtnWithBgFrame:bgFrame method:@selector(completeDateBtnPressed:)];
}

-(void)completeDateBtnPressed:(UIButton *)sender
{
    //设置时间控件的默认值
    [self setUpTheDatePickerByOneDateStr:self.sumitCarDateBtn.titleLabel.text];
    
    UIViewController *panleCon = [[UIViewController alloc] init];
    [panleCon.view addSubview:self.datePicker];
    self.popCon = [[UIPopoverController alloc] initWithContentViewController:panleCon];
    self.popCon.popoverContentSize = self.datePicker.frame.size;
    
    [self.popCon presentPopoverFromRect:CGRectMake(100, 0, 0, 30) inView:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

-(UIDatePicker *)datePicker{
    if (_datePicker == nil) {
        //创建时间控件
        _datePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 0, 280, 200)];
        _datePicker.locale = [[NSLocale alloc] initWithLocaleIdentifier:NSLocalizedString(@"Chinese", @"")];
        _datePicker.datePickerMode = UIDatePickerModeDateAndTime;
        [_datePicker addTarget:self action:@selector(dateChanged1:) forControlEvents:UIControlEventValueChanged];
    }
    return _datePicker;
}

-(void)dateChanged1:(id)sender
{
    [self.sumitCarDateBtn setTitle:[self.dateFormatter stringFromDate:self.datePicker.date] forState:UIControlStateNormal];
}

-(NSDateFormatter *)dateFormatter{
    if (_dateFormatter == nil) {
        _dateFormatter = [[NSDateFormatter alloc]init];
        [_dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    }
    return _dateFormatter;
}

//设置时间控件
-(void)setUpTheDatePicker
{
    //（2）如果时间为空，设置预计完工日为正点，预计交车日大于交车日半小时
    [self.sumitCarDateBtn setTitle:[self currentDate] forState:UIControlStateNormal];
}

//当前的时间
-(NSString *)currentDate
{
    NSDate *dates = [NSDate date];
    NSDateFormatter *format=[[NSDateFormatter alloc]init];
    [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    return [format stringFromDate:dates];
}

//通过一个字符串给时间控件设置默认值
-(void)setUpTheDatePickerByOneDateStr:(NSString *)dateStrXingCan
{
    NSDate *curDate =[[NSDate date]dateByAddingTimeInterval:60];//加一分钟
    self.datePicker.date = curDate;
    self.datePicker.minimumDate = curDate;
}

#pragma mark - 注册消息
-(void)addAllObserver
{
    [self registerNotificationForKeyBoard];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDataSubView1) name:REPAIR_ITEM_LIST_MSG_ object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDataSubView2) name:PART_LIST_MSG object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getBillDocumentList:) name:MM_GET_BILL_DOCUMENT_LIST_ object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getMileMaxInCarThrough:) name:MM_GET_MAX_MILE_IN_CAR_THROUGH_BY_VIN_ object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mm_promoteListQuitPopUpViewNotification:) name:MM_PROMOTE_LIST_QUIT_POP_UP_VIEW_MSG_ object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearPromoteListNotification:) name:MM_CLEAR_PROMOTE_LIST_ object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldValueChange:) name:UITextFieldTextDidChangeNotification object:nil];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(delActive:) name:@"delActive" object:nil];
}



#pragma mark - 结算金额汇总相关方法
//计算价格
-(void)computeTheValForJobSheet
{
    self.repairCharge = 0;
    self.firstRepairCharge = 0;
    //计算维修项目部分
   double repairToal = [self computRepairProjectList];
    self.workHourChargeTxt.text=[NSString stringWithFormat:@"%.2f",repairToal];
    //计算零件部分
    double partToal = [self computPartList];
    //计算附加项目部分
    double attachToal = [self computAttachProjectList];
    
    
    self.repairChargeTxt.text = [NSString stringWithFormat:@"%.2f",self.repairCharge];
    self.firstRepairChargeTxt.text = [NSString stringWithFormat:@"%.2f",self.firstRepairCharge];
    
    //（结算金额）：（工时费+零件费+其他费用）-（工时折扣+零件折扣+其他折扣）
    double workHourCharge = [self.workHourChargeTxt.text doubleValue];
    double partCharge = [self.partChargeTxt.text doubleValue];
    double attachCharge = [self.attachChargeTxt.text doubleValue];
    
    double workHourDiscount = [self.workHourDiscountTxt.text doubleValue];
    double partDiscount = [self.partDiscountTxt.text doubleValue];
    double attachDiscount = [self.attachChargeDiscountTxt.text doubleValue];
    
    double amount = (workHourCharge+partCharge+attachCharge)-(workHourDiscount+partDiscount+attachDiscount);
    //结算金额
    self.amountTxt.text = [NSString stringWithFormat:@"%.2f",amount];
    
    //总金额（增加）：（不区分收费区分工时费+不区分收费区分零件费+不区分收费区分其他费用）-（不区分收费区分工时折扣+不区分收费区分零件折扣+不区分收费区分其他折扣）
    double rDiscount = 0;
    double pDiscount = 0;
    double aDiscount = 0;
    if (self.selectedDiscount) {
        rDiscount = self.selectedDiscount.repairDiscount;
        if (rDiscount == 1) {
            rDiscount = 0;
        }
        pDiscount = self.selectedDiscount.partDiscount;
        if (pDiscount == 1) {
            pDiscount = 0;
        }
        aDiscount = self.selectedDiscount.attachDiscount;
        if (aDiscount == 1) {
            aDiscount = 0;
        }
    }
    double totalAmount = (repairToal + partToal + attachToal) - (repairToal*rDiscount + partToal*pDiscount + attachToal*aDiscount);
    self.totalAmountTxt.text = [NSString stringWithFormat:@"%.2f",totalAmount];
}

/** 计算维修项目部分 */
-(double)computRepairProjectList{
    NSMutableArray *projectList = [MainMenuDataModel sharedMainMenuDataModel].repairProjects;
    double totalAmout = 0;//总费用
    double workHourCharge = 0;//工时费
    double customerCharge = 0;//(自费)工时费*折扣
    if (projectList&&projectList.count>0) {
        
        NSString *chargeDiff = nil;
        for (NSDictionary *data in projectList) {
            chargeDiff = data[@"CHARGE_PARTITION_CODE"];
            /*
             *#define repairChargeCode  @"S004"//保修
              #define firstReparirChargeCode  @"S002"//首保
              #define firstReparirFreeCode  @"S003"//免费
              #define firstReparirActCode  @"S008"//市场活动
             */
            workHourCharge = [data[@"LABOUR_AMOUNT"]doubleValue];
            if ([chargeDiff isEqualToString:repairChargeCode]||[chargeDiff isEqualToString:firstReparirChargeCode]||[chargeDiff isEqualToString:firstReparirFreeCode]||[chargeDiff isEqualToString:firstReparirActCode]) {
                //不收钱
            }else{
                double DISCOUNT=data[@"DISCOUNT"]?[data[@"DISCOUNT"]doubleValue]:1;
                //乘以折扣
                customerCharge = (workHourCharge*DISCOUNT);
                totalAmout += customerCharge;

            }
        }
    }


    self.workHourChargeTxt.text = [NSString stringWithFormat:@"%.2f",customerCharge];

    return totalAmout;
}

/** 计算零件部分 */
-(double)computPartList{
    NSMutableArray *partList = [MainMenuDataModel sharedMainMenuDataModel].partList;
    double partDiscount = 0;
    double totalAmout = 0;//总费用
    double customerCharge = 0;//收费区分为自费的零件费
    if (partList&&partList.count>0) {
        double partCharge = 0;//零件费
        
        NSString *chargeDiff = nil;
        for (NSDictionary *data in partList) {
            chargeDiff = data[@"CHARGE_PARTITION_CODE"];
            partCharge = [data[@"PART_SALES_AMOUNT"]doubleValue];
            if ([chargeDiff isEqualToString:repairChargeCode]||[chargeDiff isEqualToString:firstReparirChargeCode]||[chargeDiff isEqualToString:firstReparirFreeCode]||[chargeDiff isEqualToString:firstReparirActCode]) {
                //不收钱
            }else{
                //乘以折扣
                customerCharge += (partCharge*(data[@"DISCOUNT"]? [data[@"DISCOUNT"] doubleValue]:1));
            }
//            if ([chargeDiff isEqualToString:customerChargeCode]||!chargeDiff||[chargeDiff isEqualToString:@""]) {//自费
//                customerCharge += partCharge;
//            }else if ([chargeDiff isEqualToString:repairChargeCode]){//保修
//                self.repairCharge += partCharge;
//            }else if ([chargeDiff isEqualToString:firstReparirChargeCode]){//首保
//                self.firstRepairCharge += partCharge;
//            }
            totalAmout += customerCharge;
        }
//        //计算折扣
//        double discout = 0;
//        if (self.selectedDiscount) {
//            discout = self.selectedDiscount.partDiscount;
//            if (discout == 1) {
//                discout = 0;
//            }
//        }
//        partDiscount = customerCharge * discout;
    }
    self.partChargeTxt.text = [NSString stringWithFormat:@"%.2f",customerCharge];
//    self.partDiscountTxt.text = [NSString stringWithFormat:@"%.2f",partDiscount];
    return totalAmout;
}

/** 计算附加项目件部分 */
-(double)computAttachProjectList{
    NSMutableArray *attachList = [MainMenuDataModel sharedMainMenuDataModel].attachProjects;
    double attachDiscount = 0;
    double totalAmout = 0;//总费用
    double customerCharge = 0;//收费区分为自费的零件费
    if (attachList&&attachList.count>0) {
        double attachCharge = 0;//零件费
        
        NSString *chargeDiff = nil;
        for (NSDictionary *data in attachList) {
            chargeDiff = data[@"CHARGE_PARTITION_CODE"];
            attachCharge = [data[@"ADD_ITEM_AMOUNT"]doubleValue];
            if ([chargeDiff isEqualToString:repairChargeCode]||[chargeDiff isEqualToString:firstReparirChargeCode]||[chargeDiff isEqualToString:firstReparirFreeCode]||[chargeDiff isEqualToString:firstReparirActCode]) {
                //不收钱
            }else{
                //乘以折扣
                customerCharge += (attachCharge*[data[@"DISCOUNT"]doubleValue]);
            }
//            if ([chargeDiff isEqualToString:customerChargeCode]||!chargeDiff||[chargeDiff isEqualToString:@""]) {//自费
//                customerCharge += attachCharge;
//            }else if ([chargeDiff isEqualToString:repairChargeCode]){//保修
//                self.repairCharge += attachCharge;
//            }else if ([chargeDiff isEqualToString:firstReparirChargeCode]){//首保
//                self.firstRepairCharge += attachCharge;
//            }
            totalAmout += customerCharge;
        }
//        //计算折扣
//        double discout = 0;
//        if (self.selectedDiscount) {
//            discout = self.selectedDiscount.partDiscount;
//            if (discout == 1) {
//                discout = 0;
//            }
        }
//        attachDiscount = customerCharge * discout;
//    }
    self.attachChargeTxt.text = [NSString stringWithFormat:@"%.2f",customerCharge];
//    self.attachChargeDiscountTxt.text = [NSString stringWithFormat:@"%.2f",attachDiscount];
    return totalAmout;
}



//判断输入的公里数是否超过10000KM，是返回YES，否返回NO
-(BOOL)isMileBeyond10000KM
{
    if ([self.mileageTxt.text doubleValue]-[_strMileMaxInCarThrough doubleValue] >= 10000.0)
    {
        return YES;
    }
    return NO;
}

-(BOOL)isMileBelowMileMax
{
    if ([self.mileageTxt.text doubleValue] < [_strMileMaxInCarThrough doubleValue])
    {
        return YES;
    }
    return NO;
}

//初始化获取车历最高公里数
-(void)invokeRequestForMileMaxInCarThrough
{
    NSMutableArray *arrTmp = [NSMutableArray array];
    [arrTmp addObject:@"vin"];
    [arrTmp addObject:[[MainMenuDataModel sharedMainMenuDataModel].dicJobSheetMsg objectForKey:@"vin"]];
    [HelpClass getWebServiceDataByString:MM_GET_MAX_MILE_IN_CAR_THROUGH_BY_VIN_ andArrObject:arrTmp];
}

#pragma mark - 功能确认部分
- (IBAction)functionalConfirmClicked:(UIButton *)sender {
    sender.selected = !sender.selected;
    if ([sender.currentTitle containsString:@"天窗"]) {
        self.IS_WINDOW=sender.selected?@"12781001":@"";
    }else if ([sender.currentTitle containsString:@"座椅"]){
         self.IS_CHAIR=sender.selected?@"12781001":@"";
    }else if ([sender.currentTitle containsString:@"音响"]){
        self.IS_SOUND=sender.selected?@"12781001":@"";
    }else if ([sender.currentTitle containsString:@"空调"]){
        self.IS_AIR=sender.selected?@"12781001":@"";
    }else if ([sender.currentTitle containsString:@"玻璃"]){
        self.IS_GLASS=sender.selected?@"12781001":@"";
    }else if ([sender.currentTitle containsString:@"点烟"]){
        self.IS_SMOKE=sender.selected?@"12781001":@"";
    }else if ([sender.currentTitle containsString:@"防盗器"]){
        self.IS_SAFE=sender.selected?@"12781001":@"";
    }
   
   
    
}

/** 功能确认按钮的初始化 */
-(void)setupFuncitonalButtons{
    self.funtionDicBtns = @{
                               @"1":self.windowBtn,
                               @"2":self.seatBtn,
                               @"3":self.soundsBtn,
                               @"4":self.airconditioningBtn,
                               @"5":self.glassBtn,
                               @"6":self.lighterBtn,
                               @"7":self.carBurglarBtn
                           };
}

/** 获取功能确认选中按钮的值集合 */
-(NSString *)getValuesFromSelectedBtnsWithDicArr:(NSDictionary *)btnList{
    NSMutableString *str = [[NSMutableString alloc]init];
    for (NSString *key in btnList.allKeys) {
        UIButton *btn = self.funtionDicBtns[key];
        if (btn.selected) {
            [str appendFormat:@"%@,",key];
        }
    }
    NSString *vals = @"";
    if (str.length>0) {
        NSRange range = {0,str.length-1};
        vals = [str substringWithRange:range];
    }
    return vals;
}

#pragma mark - 物品确认部分

- (IBAction)goodsConfirmBtnClicked:(UIButton *)sender {
    sender.selected = !sender.selected;
    if ([sender.currentTitle containsString:@"眼镜"]) {
        self.HAS_GLASS=sender.selected?@"12781001":@"";
    }else if ([sender.currentTitle containsString:@"备胎"]){
         self.HAS_BACK=sender.selected?@"12781001":@"";
    }else if ([sender.currentTitle containsString:@"工具"]){
         self.HAS_TOOL=sender.selected?@"12781001":@"";
    }else if ([sender.currentTitle containsString:@"千斤顶"]){
        self.HAS_LIFT=sender.selected?@"12781001":@"";
    }else if ([sender.currentTitle containsString:@"警示"]){
        self.HAS_WARN=sender.selected?@"12781001":@"";
    }else if ([sender.currentTitle containsString:@"灭火"]){
        self.HAS_EXTINGUISH=sender.selected?@"12781001":@"";
    }
    //根据物品名称更新物品列表数据
    [self updateGoodsDatasWithName:sender.titleLabel.text enable:sender.selected];

}
-(void)setTextFieldEnable:(UITextField *)txt enable:(BOOL)enable{
    txt.enabled = enable;
    if (enable) {
        txt.backgroundColor = [UIColor whiteColor];
    }else{
        txt.backgroundColor = [UIColor lightGrayColor];
        txt.text = nil;
    }
}

/** 根据物品名称更新物品列表数据 */
-(void)updateGoodsDatasWithName:(NSString *)name enable:(BOOL)enable{
    MainMenuDataModel *mainModel = [MainMenuDataModel sharedMainMenuDataModel];
    if (mainModel.arrCarryGoods.count) {
        NSDictionary *foudDic = nil;//查找到的记录
        int index = -1;
        for (int i = 0; i< mainModel.arrCarryGoods.count; i++) {
            NSDictionary *dic = mainModel.arrCarryGoods[i];
            if ([name isEqualToString:dic[@"ITEMS_NAME"]]) {
                index = i;
                foudDic = dic;
                break;
            }
        }//end for
        if (foudDic) {//如果有找到记录
            NSString *itemId =[NSString stringWithFormat:@"%@",foudDic[@"ITEM_ID"]];
            if (enable) {//选中
                if (itemId && itemId.length>0) {
                    [foudDic setValue:@"U" forKey:@"STATUS"];
                }
            }else{
                if (itemId && itemId.length>0) {
                    [foudDic setValue:@"D" forKey:@"STATUS"];
                    [foudDic setValue:@"" forKey:@"REMARK"];
                }else{
                    [mainModel.arrCarryGoods removeObjectAtIndex:index];
                }
            }
        }else{//没有找到记录
            if (enable) {
                //新加一行记录
                [self addGoddsDicWithName:name];
            }
        }
        
    }else{
        if (!mainModel.arrCarryGoods) {
            mainModel.arrCarryGoods = [NSMutableArray array];
        }
        //新加一行记录
        [self addGoddsDicWithName:name];
    }

}

-(void)addGoddsDicWithName:(NSString *)name{
    MainMenuDataModel *mainModel = [MainMenuDataModel sharedMainMenuDataModel];
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"",@"ITEM_ID",name,@"ITEMS_NAME",@"",@"REMARK",@"A",@"STATUS", nil];
    [mainModel.arrCarryGoods addObject:dic];
}



#pragma mark - 下拉框数据懒加载

/** 油量 */
-(NSDictionary *)oilCodeDic{
    if (_oilCodeDic == nil) {
        _oilCodeDic = @{
                        @"12501001":@"0",
                        @"12501002":@"1/8",
                        @"12501003":@"2/8",
                        @"12501004":@"3/8",
                        @"12501005":@"4/8",
                        @"12501006":@"5/8",
                        @"12501007":@"6/8",
                        @"12501008":@"7/8",
                        @"12501009":@"FULL",
                        };
    }
    return _oilCodeDic;
}

-(NSDictionary *)oilDic{
    if (_oilDic == nil) {
        _oilDic = @{
                    @"0":@"12501001",
                    @"1/8":@"12501002",
                    @"2/8":@"12501003",
                    @"3/8":@"12501004",
                    @"4/8":@"12501005",
                    @"5/8":@"12501006",
                    @"6/8":@"12501007",
                    @"7/8":@"12501008",
                    @"FULL":@"12501009",
                    };
    }
    return _oilDic;
}

-(NSArray *)oilNamesArr{
    if (_oilNamesArr == nil) {
        _oilNamesArr = @[@"0",@"1/8",@"2/8",@"3/8",@"4/8",@"5/8",@"6/8",@"7/8",@"FULL"];
    }
    return _oilNamesArr;
}

/** 服务顾问 */
-(NSMutableArray *)serviceAdviserArr{
    if (_serviceAdviserArr == nil) {
        _serviceAdviserArr= [NSMutableArray array];
        _serviceAdviserDic = [NSMutableDictionary dictionary];
        _serviceAdviserCodeDic = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"SERVICE_ADVISOR"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            [_serviceAdviserArr addObject:name];
            [_serviceAdviserDic setObject:val forKey:name];
            [_serviceAdviserCodeDic setObject:name forKey:val];
        }
    }
    return _serviceAdviserArr;
}
-(NSMutableArray *)sexArr
{
    if (!_sexArr) {
        _sexArr= [NSMutableArray array];
        _sexDic = [NSMutableDictionary dictionary];
        _sexCodeDic = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"GENDER"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            [_sexArr addObject:name];
            [_sexDic setObject:val forKey:name];
            [_sexCodeDic setObject:name forKey:val];
        }
    }
        return _sexArr;
}
/** 工单类型 */
-(NSMutableArray *)jobsheetTypeArr{
    if (_jobsheetTypeArr == nil) {
        _jobsheetTypeArr= [NSMutableArray array];
        _jobsheetTypeDic = [NSMutableDictionary dictionary];
        _jobsheetTypeCodeDic = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"TM_RO_TYPE"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            [_jobsheetTypeArr addObject:name];
            [_jobsheetTypeDic setObject:val forKey:name];
            [_jobsheetTypeCodeDic setObject:name forKey:val];
        }
    }
    return _jobsheetTypeArr;
}

/** 维修分类 */
-(NSMutableArray *)repairTypeArr{
    if (_repairTypeArr == nil) {
        _repairTypeArr= [NSMutableArray array];
        _repairTypeDic = [NSMutableDictionary dictionary];
        _repairTypeCodeDic = [NSMutableDictionary dictionary];
        NSMutableArray *arr = [self readershuDICimform][@"TM_REPAIR_TYPE_MAIN"];
        for (NSDictionary *dic in arr) {
            NSString *name = dic[@"NAME"];
            NSString *val = dic[@"CODE"];
            [_repairTypeArr addObject:name];
            [_repairTypeDic setObject:val forKey:name];
            [_repairTypeCodeDic setObject:name forKey:val];
        }
    }
    return _repairTypeArr;
}

/** 优惠模式 */
-(NSMutableArray *)discountNameArr{
    if (_discountNameArr == nil) {
        _discountNameArr = [NSMutableArray array];
        NSMutableArray *arr = [self readershuDICimform][@"TM_DISCOUNT_MODEL"];
        _discountModeDic = [NSMutableDictionary dictionary];
        _discountModeCodeDic = [NSMutableDictionary dictionary];
        for (NSDictionary *dic in arr) {
            DiscountItem *discount = [[DiscountItem alloc]init];
            NSString *name = dic[@"DISCOUNT_MODE_NAME"];
            [_discountNameArr addObject:name];
            discount.name = name;
            discount.code = dic[@"DISCOUNT_MODE_CODE"];
            discount.repairDiscount = [dic[@"LABOUR_AMOUNT_DISCOUNT"]doubleValue];
            discount.partDiscount = [dic[@"REPAIR_PART_DISCOUNT"]doubleValue];
            discount.attachDiscount = [dic[@"ADD_ITEM_DISCOUNT"]doubleValue];
            [_discountModeDic setObject:discount forKey:name];
            [_discountModeCodeDic setObject:name forKey:discount.code];
        }
    }
    return _discountNameArr;
}

/** 工时单价 */
-(NSMutableArray *)labourPrices{
    if (_labourPrices == nil) {
        _labourPrices= [NSMutableArray array];
        NSMutableArray *arr = [self readershuDICimform][@"TM_LABOUR_PRICE"];
        for (NSDictionary *dic in arr) {
            NSString *name = [dic[@"NAME"]stringValue];
//            NSString *val = dic[@"CODE"];
            [_labourPrices addObject:name];
        }
    }
    return _labourPrices;
}

-(NSMutableDictionary *)readershuDICimform
{
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path=[paths objectAtIndex:0];
    NSString *str=[path stringByAppendingPathComponent:@"Dic.text"];
    dic=[NSMutableDictionary dictionaryWithContentsOfFile:str];
    //nslog(@"%@",dic);
    return dic;
}

#pragma mark -picRecodeViewController代理方法
-(void)defectListChanged{
    //重新标记界面上的标记
    [self createRemarksOnOutCheckBtn];
    
    //缺陷列表
    [subViewPicRemarks setNeedsDisplay];
}

#pragma mark - mm_jobItemGroupViewController代理方法
-(void)repairAndPartListDataChanged{
    [self.subView1 setNeedsDisplay];
    [self.subView2 setNeedsDisplay];
    [self computeTheValForJobSheet];
}

#pragma mark - mm_addAndModifyViewControllerDelegate代理方法
-(void)repairProjectListDataChanged{
    [self.subView1 setNeedsDisplay];
    [self computeTheValForJobSheet];
}

-(void)parttListDataChanged{
    [self.subView2 setNeedsDisplay];
    [self computeTheValForJobSheet];
}

#pragma mark -三包验证
- (IBAction)sanbaoCheck {
    [SVProgressHUD showWithStatus:@"正在查询...."];
    //保存数据
    NSDictionary *param = @{
                            @"VIN":self.vinLbl.text,
                            @"IN_MILEAGE":self.mileageTxt.text,
                            @"OP_FLAG":@"1",
                            };
    
    [MyAFNetWorkManager postWithParam:param andAction:@"DRSERVICE18" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
        [SVProgressHUD dismiss];
        NSString *msg = nil;
        int success = [obj[@"SUCCESS"]intValue];
        if (error||!success) {
            msg = @"查询出错";
        }else{
            NSDictionary *info = obj[@"TT_TRIPLE_GUARANTEE_INFO"];
            if (info) {
                NSString *guarantee = info[@"IS_TRIPLE_GUARANTEE"];
                msg = [guarantee isEqualToString:@"是"]? @"是三包车辆" : @"非三包车辆";
            }else{
                msg = @"否";
            }
        }
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示信息" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }];
}
- (IBAction)clickRepairHistory:(id)sender {
    WEAKSELF;
    [SVProgressHUD showWithStatus:@"请等待...."];
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:3];
    //    [param setObject:@(0) forKey:@"FROM"];
    //    [param setObject:@(10) forKey:@"TO"];
    [param setObject:self.vinLbl.text.length?self.vinLbl.text:@"" forKey:@"VIN"];
    
    [MyAFNetWorkManager postWithParam:param andAction:@"QUERY_REPAIR_ORDER_PAD" finish:^(NSData *data, NSDictionary *obj, NSError *error) {
         [SVProgressHUD dismiss];
        if (!error) {
            NSMutableArray *datas = (NSMutableArray *)obj[@"TT_REPAIR_ORDER"];
            
//            self.historyArray = datas;
//            [self.hostoryView.repairTableView reloadData];
            if (0 == [datas count])
            {
                UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"该车没有维修车历！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alerVeiw show];
                
                return;
            }
            
            CarCalendarQueryViewController *vc = [[CarCalendarQueryViewController alloc] initWithNibName:@"CarCalendarQueryViewController" bundle:nil];
            vc.allHistory =datas;
            [weakSelf.navigationController pushViewController:vc animated:YES];
           
        }else{
            [SVProgressHUD dismiss];
            NSLog(@"%@",error);
        }
        
    }];
}
#pragma mark --HJMakeAppointmentSelectViewDelegate
-(void)makeAppointmentSelectView:(HJMakeAppointmentSelectView *)makeAppointmentSelectView clickSelctCell:(HJNotConmmingPadModel *)notConmmingPadModel
{
    self.yuyueOrderLabel.text=notConmmingPadModel.BOOKING_ORDER_NO;
}
#pragma mark --- repair-activeDel
-(void)delActive:(NSNotification *)notification{
    NSDictionary * dic= notification.object;
    CGFloat w = 600;
    _reasonView= [[ReasonView alloc]initWithFrame:CGRectMake((1024-w)/2, 400, w, 300)];
    _reasonView.delegate = self;
    _reasonView.backgroundColor = [UIColor whiteColor];
    _reasonView.dataDic = dic;
    _reasonView.reasonNameArr = self.reasonNameArr;
    _reasonView.reasonCodeArr = self.reasonCodeArr;

    [self.view addSubview:_reasonView];
    
}

-(void)ReasonViewClickCanelBtn{
    [_reasonView removeFromSuperview];
    _reasonView = nil;

}

-(void)ReasonViewClickMakeSureBtn{
    [_reasonView removeFromSuperview];
    _reasonView = nil;
    [self repairAndPartListDataChanged];

}
-(NSMutableArray *)reasonCodeArr{
    if (_reasonCodeArr == nil) {
        _reasonCodeArr = [[NSMutableArray alloc]init];
    }
    return _reasonCodeArr;
}
-(NSMutableArray *)reasonNameArr{
    if (_reasonNameArr == nil) {
        _reasonNameArr = [[NSMutableArray alloc]init];
    }
    return _reasonNameArr;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
@end

